# GCP - Init Functions
# vim:set filetype=sh:
# shellcheck shell=sh

# NOTE: overrides lib/tiny-cloud function
# 	GCP ssh keys have a leading "<login>:" we should check/honor
init__set_ssh_keys() {
	mkdir -p "$ROOT/run/tiny-cloud"
	local tmp_dir=$(mktemp -d "$ROOT/run/tiny-cloud/sshkeys-XXXXXX")
	chmod 700 "$tmp_dir"
	local userkey
	local user
	local key
	local pwent
	local group
	local tmp_file
	local found=
	imds @ssh-keys | while IFS= read -r userkey; do
		user=$(echo "$userkey" | cut -d: -f1)
		key=$(echo "$userkey" | cut -d: -f2-)
		if [ -z "$user" ] || ! pwent="$(getent passwd "$user")"; then
			log -i -t "$phase" warning "$ACTION: skipping SSH key for $user"
			continue
		fi
		group=$(echo "$pwent" | cut -d: -f4)
		tmp_file="$tmp_dir/$user"
		touch "$tmp_file"
		chmod 600 "$tmp_file"
		$MOCK chown -R "$user:$group" "$tmp_file"
		echo "$key" >> "$tmp_file"
	done
	local ssh_dir
	for tmp_file in "$tmp_dir"/*; do
		[ -f "$tmp_file" ] || continue
		user=$(basename "$tmp_file")
		pwent="$(getent passwd "$user")"
		group=$(echo "$pwent" | cut -d: -f4)
		ssh_dir="$ROOT$(echo "$pwent" | cut -d: -f6)/.ssh"
		if [ ! -d "$ssh_dir" ]; then
			mkdir -p "$ssh_dir"
			$MOCK chown -R "$user:$group" "$ssh_dir"
			chmod 700 "$ssh_dir"
		fi
		cp -a "$tmp_file" "$ssh_dir/authorized_keys"
		log -i -t "$phase" info "$ACTION: installed ssh keys for $user"
		if [ "$user" = "$CLOUD_USER" ]; then
			found=2
		elif [ "$found" != 2 ]; then
			found=1
		fi
	done
	rm -rf "$tmp_dir"
	if [ -z "$found" ]; then
		log -i -t "$phase" warning "$ACTION: no SSH keys installed"
	elif [ "$found" != 2 ]; then
		log -i -t "$phase" warning "$ACTION: no SSH keys found for $CLOUD_USER"
	fi
}
