#!/bin/bash
#
# Author: Georg Voell - georg.voell@standby.cloud
# Version: @(#)createkeys-api 1.0.0 21.11.2021 (c)2021 Standby Cloud
#
# Generate all needed SSH Keys to access Oracle Cloud via Web-API
# Usage: First parameter is 'username' and second parameter is 'passphrase'
#
# Version history:
#
# V 1.0.0 21.11.2021 New version
#

# Set HOME if it isn't defined
if [ "$HOME" = "" ]; then
	export USER=`whoami`	# Current user
	export HOME=$(eval echo ~${USER})
fi

# Set PATH to something useful
PATH=${HOME}/.local/bin:${HOME}/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:$PATH

username=${1}
passphrase=${2}

keygenurl="https://standby.cloud/ssh-keygen/keygen.pl"  # Web-API
targetdir="/tmp"                                        # Download here

# Check if we have jq (https://stedolan.github.io/jq/) and curl in PATH
jq=`which jq 2>/dev/null`
curl=`which curl 2>/dev/null`

# Function errormsg
function errormsg() {
	local normal='\033[0m'
	local redcol='\033[0;91m' # Highlighted red
	
	local number=${1}         # Error Number
	local errmsg=${2}         # Error Message
	local errrsn=${3}         # Error Reason

	if [ "$errrsn" = "" ]; then
		printf "${redcol}ERROR(%02d): ${errmsg}${normal}\n" $number > /dev/stderr
	else
		printf "${redcol}ERROR(%02d): ${errmsg} (${errrsn})${normal}\n" $number > /dev/stderr
	fi
}

# Returns a URI string for passing to curl
function UriEncode() {
	local locstr=${1}
	
	if [ "$locstr" != "" ]; then
		# We can do translation only if we have jq in PATH
		if [ "$jq" != "" ]; then
			$jq -nr --arg v "$locstr" '$v|@uri'
		else
			# No translation - Please use only allowed acii chars in that case
			echo "$locstr"
		fi
	fi
}

# Main
exitcode=0

if [ "$curl" = "" ]; then
	exitcode=1
	errormsg $exitcode "No 'curl' in '$PATH'."
else
	if [ "$username" = "" ]; then
		exitcode=2
		errormsg $exitcode "Please specify a username as first parameter."
	else
		if [ "$passphrase" != "" ]; then
			# Check length of string must be at least 5 chars
			result=`printf "${#passphrase}"`
			if [ $result -lt 5 ]; then
				exitcode=3
				errormsg $exitcode "Passphrase has less then 5 chars." "Passphrase: '$passphrase'"
				exit $exitcode
			fi
		fi

		targetfile="${targetdir}/${username}.zip"
		if [ -f "$targetfile" ]; then
			exitcode=4
			errormsg $exitcode "File '$targetfile' already exists."
		else
			uriusername=`UriEncode "$username"`
			
			if [ "$passphrase" != "" ]; then
				uripassphrase=`UriEncode "$passphrase"`
				myurl="${keygenurl}?username=${uriusername}&passphrase=${uripassphrase}"
			else
				myurl="${keygenurl}?username=${uriusername}"
			fi

			# Call Web-API
			curl -k -L -s "$myurl" -o "$targetfile"
			stat=$?
			
			if [ $stat -gt 0 ]; then
				exitcode=5
				errormsg $exitcode "Trouble with internet connection." "Exit code from 'curl': $stat"
			else
				# Check if download was successful
				if [ ! -f "$targetfile" ]; then
					exitcode=6
					errormsg $exitcode "Could not download keys."
				else
					# Check if zip is corrupt
					unzip -q -t "$targetfile" >/dev/null 2>&1
					stat=$?
					
					if [ $stat -gt 0 ]; then
						# Try to get error message
						result=`grep ">Application Error:" "$targetfile"`
						if [ "$result" != "" ]; then
							reason=`echo "$result" | cut -d'>' -f2 | cut -d'<' -f1`
						else
							reason="Reason unknown"
						fi
						
						exitcode=7
						errormsg $exitcode "Zip corrupted." "$reason"
						
						# Delete the corrupt downloaded file
						rm -f "$targetfile"
					else
						# Download was succcessful - Display success message
						echo "Downloaded keys to '$targetfile'. Please use 'unzip' to extract files."
					fi
				fi
			fi
		fi
	fi
fi

# Leave with exitcode
exit $exitcode

