# 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() {
	local tmp_dir userkey user key keys tmp_file found=
	bootstrap_tmp_init || return
	tmp_dir=$(mktemp -d "$TINY_CLOUD_TMP_DIR/sshkeys.XXXXXX") || return
	keys=$(imds @ssh-keys) || return
	while IFS= read -r userkey; do
		user=${userkey%%:*}
		key=${userkey#*:}
		if [ -z "$user" ] || ! getent passwd "$user" >/dev/null; then
			log warning -i -t "$phase" "$ACTION: skipping SSH key for $user"
			continue
		fi
		(umask 077; printf '%s\n' "$key" >> "$tmp_dir/$user") || return
	done <<-EOT
		$keys
	EOT
	for tmp_file in "$tmp_dir"/*; do
		[ -f "$tmp_file" ] || continue
		user=${tmp_file##*/}
		keys=$(cat "$tmp_file") || return
		install_ssh_keys "$user" "$keys" || return
		log info -i -t "$phase" "$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 warning -i -t "$phase" "$ACTION: no SSH keys installed"
	elif [ "$found" != 2 ]; then
		log warning -i -t "$phase" "$ACTION: no SSH keys found for $CLOUD_USER"
	fi
}
