#!/bin/sh
set -e

WRITE=0
PREFIX=
: "${SCRIPT_PATH:=$(dirname "$0")}"

while [ -n "$1" ]
do
	case "$1" in
		-h | --help)
			printf '\033[0mUsage: \033[1m%s\033[0m [\033[1m--help\033[0m] [ \033[1m--install\033[0m ] [ \033[1m--prefix\033[0m \033[4mDIR\033[0m ]\n' "${ARGV0:-$0}"
			printf '\n'
			printf '   This program will append the SSH key from the OpenNebula context disk image to authorized_keys.\n'
			printf '\n'
			printf '   \033[1m--help   \033[0m   \033[0m	Show this help text.\n'
			printf '   \033[1m--install\033[0m   \033[0m	Write files for first boot.\n'
			printf '   \033[1m--prefix \033[0;4mDIR\033[0m	Write to directory specified in \033[4mDIR\033[0m.\n'
			printf '\n'
			return;;
		--install)
			if [ "$WRITE" = 1 ]
			then
				printf '\033[0m%s: \033[1m--install\033[0m is specified more than once.\n' "${ARGV0:-$0}" >&2
				exit 2
			fi
			WRITE=1
			shift;;
		--prefix)
			if [ -n "$PREFIX" ]
			then
				printf '\033[0m%s: \033[1m--prefix\033[0m is specified more than once.\n' "${ARGV0:-$0}" >&2
				exit 2
			fi
			if [ -z "$2" ]
			then
				printf '\033[0m%s: \033[1m--prefix\033[0m specified without a prefix.\n' "${ARGV0:-$0}" >&2
				exit 2
			fi
			PREFIX="$(printf %s "$2" | sed 's@[/]*$@@')"
			shift 2;;
		*)
			printf '\033[0m%s: Unexpected argument \033[1m%s\033[0m.\n' "${ARGV0:-$0}" "$1" >&2
			exit 2
	esac
done

getent="$(. "${SCRIPT_PATH}/userconf-getent.sh")"
user="$(getent passwd "$user" | cut -d: -f6 | sed 's@^[/]*@@')"
homedir="$PREFIX/$(printf %s "$getent" | cut -d: -f1)"
sshkey="$(. "${SCRIPT_PATH}/userconf-sshkey.sh")"
if [ -n "$sshkey" ]
then
	if [ "$WRITE" = 0 ]
	then
		printf '# %s/.ssh/authorized_keys\n%s\n' "$homedir" "$sshkey"
		return
	fi

	# TODO if the user does not exist, should we create it?
	# What should the home directory be, should it have its own group,
	# should we create the home directory as a ZFS volume if ZFS is used?

	group="$(printf %s "$getent" | cut -d: -f4 | grep '^[0-9]*$')"
	if [ -z "$group" ]
	then
		printf '%s: User %s has no numeric group ID\n' "${ARGV0:-$0}" "$user" >&2
		exit 4
	fi

	mkdir -p "$homedir/.ssh"
	if [ -f "$homedir/.ssh/authorized_keys" ]
	then
		# Check if the key is already listed
		grep -Fqx "$sshkey" "$homedir/.ssh/authorized_keys" && return

		# Check that authorized_keys ends with a newline
		# -e writes a literal $ for every \n,
		# so we check that the last character on the last line is $
		if tail -n1 "$homedir/.ssh/authorized_keys" | cat -e | grep -q '\$$'
		then
			true
		else
			printf '\n' >>"$homedir/.ssh/authorized_keys"
		fi
	fi

	printf '%s\n' "$sshkey" >>"$homedir/.ssh/authorized_keys"
	chown "$user:$group" "$homedir/.ssh/" "$homedir/.ssh/authorized_keys"
fi
