# 21-addpass
# prompt and set password or SSH public key for admin user

log "TRACE 21-addpass: script started"

PWusr="hybadmin"
DefPW="WebG@tew@y#" # default hybadmin password for auto-firstboot
MANUAL_BACK=0

log "TRACE 21-addpass: AUTOINST='$AUTOINST'"

if [ -n "$AUTOINST" ] ; then
	log "TRACE 21-addpass: taking auto-firstboot path"
	# auto-firstboot: no prompt, fixed default password
	P1="$DefPW"
	SetPW # set password in system
else
	log "TRACE 21-addpass: taking manual-firstboot path"
	# manual-firstboot: prompt user for auth method
	while(true) ; do
		log "TRACE 21-addpass: calling GetAuthMethod"
		GetAuthMethod || {
			if [ "$MANUAL_BACK" = "1" ] ; then
				BACK_TO="30-network"
				return 1
			fi
		}

		log "TRACE 21-addpass: GetAuthMethod returned, AUTH_METHOD='$AUTH_METHOD' MANUAL_BACK='$MANUAL_BACK'"

		if [ "$AUTH_METHOD" = "pubkey" ] ; then
			log "TRACE 21-addpass: entering pubkey flow"
			# SSH public key flow
			while(true) ; do
				GetPubKey && break
				[ "$MANUAL_BACK" = "1" ] && break # go back to auth method menu
			done
			[ "$MANUAL_BACK" = "1" ] && continue # back to auth method menu
			break
		else
			log "TRACE 21-addpass: entering password flow"
			# password flow (existing behavior)
			while(true) ; do
				GetPW || {
					if [ "$MANUAL_BACK" = "1" ] ; then
						break # go back to auth method menu (keep MANUAL_BACK=1)
					fi
				}
				[ "$MANUAL_BACK" = "1" ] && break
				[ "$P1" == "$DefPW" ] && break
				ChkPW && break
			done
			[ "$MANUAL_BACK" = "1" ] && continue
			SetPW # set password in system
			break
		fi
	done
fi

unset P1 P2 LEN PWusr AUTH_METHOD
wipefiles $tempfile

