# 01-password
# functions:
# ChkPW: check password for quality
# GetPW: prompt user for password
# FinPW: loop to get good password (uses ChkPW & GetPW)
# SetPW: set password in system

#----------------------------------------------------------------------
# check quality of password
# Entry: P1 & P2 = password
# Returns: 0 if p/w is good, !0 otherwise
ChkPW() {
   echo "${P1}"  | cracklib-check >${tempfile} 2>&1
   Pass=$(grep -q ": OK\$" $tempfile && echo "OK" || echo $"fail")
   LEN=$(echo ${#P1})

   # PW too short?
   if [ $LEN -lt 8 ] ; then
      $DIALOG --clear --backtitle "$BT" --title "  Error  " --msgbox \
         "\n Password length $LEN too short.\n\n Minimum of 8 characters required." $H1 $W1
      log "Password length $LEN too short."

   # two PWs don't match?
   elif [ "x$P1" != "x$P2" ] ; then
      $DIALOG --clear --backtitle "$BT" --title "  Error  " --msgbox \
         "\n Two passwords do not match." $H1 $W1
      log "Two passwords do not match."

   # PW based on dictionary word?
   elif [ "x$Pass" != "xOK" ] ; then
      $DIALOG --clear --backtitle "$BT" --title "  Error  " --msgbox \
         "\n Password is based on dictionary word." $H1 $W1
      log "Password is based on dictionary word."

   # all tests pass, its good
   else
      return 0
   fi

   # failed a test, its bad
   return 1
} # ChkPW

#----------------------------------------------------------------------
# prompt user for password (two times)
# Entry: DefPW default p/w used if auto-install, 
#        PWUsr username for this password
#        temfile used to capture input
# Exit: P1 & P2 set to password
GetPW() {
      P1=""
      P2=""
      MANUAL_BACK=0

      while true ; do
         : > "$tempfile"
         # enter password
         $DIALOG \
           --ok-label "Next" \
                --extra-button \
                --extra-label "Back" \
           --clear \
           --visit-items \
           --backtitle "$BT" \
           --title " Create $PWusr Password " \
           --insecure \
           --nocancel \
           --passwordform "\n\
 Password should be difficult to guess.\n\
 Password must be minimum 8 characters.\n\
[Tab: Switch fields | Enter: Accept | Arrows: Navigate]\n\n\
 Enter $PWusr password:" \
           $H1 $W1 2 \
           "Password:" 1 1 ""   1 20 16 15 \
           "Reenter :" 2 1 ""   2 20 16 15 \
           2>"$tempfile"
         k=$?
         log "TRACE GetPW: dialog returned k=$k PWusr='$PWusr'"

             # manual-firstboot back to previous screen
             if [ "$k" = "3" ] ; then
                  MANUAL_BACK=1
                  return 1
             fi

         # timeout / error / cancel -> re-prompt (do NOT set default password)
         if [ "$k" -ne 0 ]; then
            return 1
         fi

         P1=$(head -1 "$tempfile")
         P2=$(tail -1 "$tempfile")
         return 0
      done
} # GetPW

#----------------------------------------------------------------------
# set password in system
# Entry: P1 is password to set
#        PWusr is user to be set with this password
# Returns: 0 if success
SetPW() {
   echo "$P1" | /bin/passwd --stdin $PWusr >/tmp/e1 2>/tmp/e2
   if [ $? -ne 0 ] ; then
      /bin/passwd --lock $PWusr
      show "   Failed to set the $PWusr password"
      show "   $(cat /tmp/e2)"
      sleep .1
      return 1
   else
      log "   set the $PWusr password successfully"
      log "   $(cat /tmp/e1)"
   fi
   rm -f /tmp/{e1,e2}
} # SetPW

#----------------------------------------------------------------------
# prompt user for auth method: password or SSH public key
# Entry: PWusr is the username
# Exit: AUTH_METHOD set to "password" or "pubkey"
GetAuthMethod() {
   log "TRACE GetAuthMethod: entering function, PWusr='$PWusr' DIALOG='$DIALOG'"
   AUTH_METHOD=""
   MANUAL_BACK=0

   $DIALOG \
     --ok-label "Next" \
     --extra-button \
     --extra-label "Back" \
     --clear \
     --nocancel \
     --visit-items \
     --default-item "1" \
     --backtitle "$BT" \
     --title " $PWusr Authentication Method " \
     --menu "\n Select authentication method for $PWusr:\n " $H1 $W1 2 \
     1 "Set Password" \
     2 "Add SSH Public Key" \
     2>"$tempfile"
   k=$?
   log "TRACE GetAuthMethod: dialog returned k=$k selection='$(cat "$tempfile" 2>/dev/null)'"

   if [ "$k" = "3" ] ; then
      MANUAL_BACK=1
      return 1
   fi

   

   a=$(cat "$tempfile")
   log "TRACE GetAuthMethod: user selected '$a'"
   case "$a" in
      1) AUTH_METHOD="password" ;;
      2) AUTH_METHOD="pubkey"   ;;
   esac
   log "TRACE GetAuthMethod: returning AUTH_METHOD='$AUTH_METHOD'"
   return 0
}

#----------------------------------------------------------------------
# prompt user for an SSH public key via an HTTPS URL.
# Only https:// URLs are accepted;
# Entry: PWusr is the username
#        tempfile used to capture input
# Exit: 0 on success, 1 on failure/back
GetPubKey() {
   MANUAL_BACK=0
   local keyfile="/tmp/pubkey_material.tmp"
   local source_desc=""

   while true ; do
      $DIALOG \
        --ok-label "Next" \
        --extra-button \
        --extra-label "Back" \
        --clear \
        --nocancel \
        --backtitle "$BT" \
        --title " SSH Public Key for $PWusr " \
                  --inputbox "\n Enter a public key URL.\n Supported protocol : https\n" \
        $H1 $W1 \
        2>"$tempfile"
      k=$?

      if [ "$k" = "3" ] ; then
         MANUAL_BACK=1
         return 1
      fi

      if [ "$k" = "255" ] || grep -iq timeout "$tempfile" ; then
         return 1
      fi

      # first non-empty, trimmed line of input
      INPUT="$(grep -m1 -v '^[[:space:]]*$' "$tempfile" | sed 's/^[[:space:]]*//; s/[[:space:]]*$//')"

      if [ -z "$INPUT" ] ; then
         $DIALOG --clear --backtitle "$BT" --title "  Error  " --msgbox \
            "\n No URL provided.\n\n Enter an HTTPS URL, e.g.:\n https://example.com/id_ed25519.pub" $H1 $W1
         log "pubkey: empty input"
         continue
      fi

      if ! echo "$INPUT" | grep -qiE '^https://' ; then
         $DIALOG --clear --backtitle "$BT" --title "  Error  " --msgbox \
            "\n Unsupported URL.\n\n Only HTTPS URLs are accepted.\n Example: https://example.com/id_ed25519.pub" $H1 $W1
         log "pubkey: rejected non-HTTPS input '$INPUT'"
         continue
      fi

      rm -f "$keyfile" /tmp/curl_err

      source_desc="URL $INPUT"
      $DIALOG --backtitle "$BT" --title " Downloading " --infobox \
         "\n Downloading key from:\n $INPUT\n" $H1 $W1
      curl -k -sSfL --max-time 15 -o "$keyfile" "$INPUT" 2>/tmp/curl_err
      rc=$?
      if [ $rc -ne 0 ] ; then
         case $rc in
            3)  emsg="The URL is malformed." ;;
            6)  emsg="Could not resolve host. Check the address, DNS, or network." ;;
            7)  emsg="Failed to connect to the server. Check network, host, or port." ;;
            22) emsg="Server returned an HTTP error (e.g. 404 Not Found or 403 Forbidden)." ;;
            28) emsg="Connection timed out." ;;
            35) emsg="TLS/SSL connection error." ;;
            60) emsg="TLS certificate could not be verified." ;;
            *)  emsg="Download failed (curl error $rc)." ;;
         esac
         $DIALOG --clear --backtitle "$BT" --title "  Error  " --msgbox \
            "\n $emsg\n\n $(cat /tmp/curl_err 2>/dev/null)" $H1 $W1
         log "pubkey: download failed (curl rc=$rc) from $INPUT"
         rm -f "$keyfile" /tmp/curl_err
         continue
      fi

      # downloaded but empty?
      if [ ! -s "$keyfile" ] ; then
         $DIALOG --clear --backtitle "$BT" --title "  Error  " --msgbox \
            "\n The downloaded file is empty.\n\n No key data was found at:\n $INPUT" $H1 $W1
         log "pubkey: downloaded file empty from $INPUT"
         rm -f "$keyfile" /tmp/curl_err
         continue
      fi

      # validate: must contain at least one line starting with a known key type
      if ! grep -qE '^(ssh-rsa|ssh-ed25519|ecdsa-sha2|ssh-dss) ' "$keyfile" ; then
         $DIALOG --clear --backtitle "$BT" --title "  Error  " --msgbox \
            "\n No public key was found in $source_desc.\n\n Start the key with ssh-ed25519, ssh-rsa,\n ecdsa-sha2, or ssh-dss." $H1 $W1
         log "pubkey: no key-type prefix found in $source_desc"
         rm -f "$keyfile" /tmp/curl_err
         continue
      fi

      # A downloaded file may contain several keys (plus comments / blank
      # lines). Check every line and keep only the ones that (a) start with a
      # supported key type and (b) actually parse as a real key. The validated
      # keys are collected into "$keyfile.valid".
      : > "$keyfile.valid"
      VALIDKEYS=0
      SKIPPED=0
      while IFS= read -r line ; do
         line="$(printf '%s' "$line" | sed 's/^[[:space:]]*//; s/[[:space:]]*$//')"
         [ -z "$line" ] && continue
         case "$line" in \#*) continue ;; esac
         case "$line" in
            ssh-rsa\ *|ssh-ed25519\ *|ecdsa-sha2*\ *|ssh-dss\ *) ;;
            *) SKIPPED=$((SKIPPED+1)); continue ;;
         esac
         if command -v ssh-keygen >/dev/null 2>&1 ; then
            printf '%s\n' "$line" > /tmp/pk_one.tmp
            if ! ssh-keygen -l -f /tmp/pk_one.tmp >/dev/null 2>&1 ; then
               SKIPPED=$((SKIPPED+1))
               continue
            fi
         fi
         printf '%s\n' "$line" >> "$keyfile.valid"
         VALIDKEYS=$((VALIDKEYS+1))
      done < "$keyfile"
      rm -f /tmp/pk_one.tmp

      if [ "$VALIDKEYS" -eq 0 ] ; then
         $DIALOG --clear --backtitle "$BT" --title "  Error  " --msgbox \
            "\n No valid public key was found in $source_desc.\n\n Enter a full key line starting with ssh-ed25519,\n ssh-rsa, ecdsa-sha2, or ssh-dss." $H1 $W1
         log "pubkey: no valid keys found in $source_desc (skipped=$SKIPPED)"
         rm -f "$keyfile" "$keyfile.valid" /tmp/curl_err
         continue
      fi

      mv -f "$keyfile.valid" "$keyfile"
      break
   done

   # install the validated keys, skipping duplicates
   USERHOME=$(eval echo "~$PWusr")
   mkdir -p "$USERHOME/.ssh"
   chmod 700 "$USERHOME/.ssh"
   touch "$USERHOME/.ssh/authorized_keys"
   ADDED=0
   DUP=0
   while IFS= read -r line ; do
      [ -z "$line" ] && continue
      if grep -qxF "$line" "$USERHOME/.ssh/authorized_keys" ; then
         DUP=$((DUP+1))
      else
         echo "$line" >> "$USERHOME/.ssh/authorized_keys"
         ADDED=$((ADDED+1))
      fi
   done < "$keyfile"
   chmod 600 "$USERHOME/.ssh/authorized_keys"
   chown -R "$PWusr:$PWusr" "$USERHOME/.ssh"
   rm -f "$keyfile" /tmp/curl_err

   KEYCOUNT=$(grep -cE '^(ssh-rsa|ssh-ed25519|ecdsa-sha2|ssh-dss) ' "$USERHOME/.ssh/authorized_keys")
   log "   Installed SSH public key(s) for $PWusr from $source_desc: added=$ADDED duplicate=$DUP skipped=$SKIPPED total=$KEYCOUNT"

   $DIALOG --backtitle "$BT" --title " SSH Key Installed " --infobox \
      "\n SSH keys updated for $PWusr.\n\n Added: $ADDED   Duplicate: $DUP\n Skipped: $SKIPPED   Total: $KEYCOUNT" $H1 $W1
   sleep 2
   return 0
} # GetPubKey