# 40-hostname
# prompt for input and set system hostname

# Setup the hostname of the system into:
#   /etc/hosts
#   /etc/sysconfig/network
#   /bin/hostname 
# Requires that networking and an IPV4 address exists
# exports HOSTNAME

DH="slos1test" # default hostname

# kludge for auto-install
if [ -n "$AUTOINST" ] ; then
   if [ "$AI_HOST" == "N" ] ; then
      log "hostname: skipping hostname setup."
   else
      HOST="$AI_HOSTNAME"
      [ -z "$HOST" ] && HOST="$DH"
      log "hostname: Setting hostname to $HOST"
      hostname $HOST
      hostnamectl set-hostname $HOST
      #nmcli con modify  my-office ipv4.dhcp-hostname host-name ipv6.dhcp-hostname host-name
   fi

# end-kludge for auto-install
else
    P1="$DH"
    while true ; do
       $DIALOG --clear --backtitle "$BT" --title "Hostname Setup" \
          --visit-items \
          --nocancel \
          --extra-button \
          --extra-label "Back" \
          --max-input 64 \
          --ok-label "Next" \
          --inputbox "\nEnter Hostname:\n\nHint: Use arrow keys in fields. Press Tab to move to Next/Back.\n\nDefault: $P1\n" \
          $H1 $W1 "$P1" 2> $tempfile

       k=$?

       if [ "$k" = "3" ] ; then
          log "firstboot:hostname: user selected Back"
          BACK_TO="21-addpass"
          return 1
       fi

       # timeout? set default
       if [ "$k" = "255" ] || grep -iq timeout $tempfile ; then
          HOST="$P1"
       else
          HOST=$(cat $tempfile)
       fi
       break
    done

    # Check hostname contains only alphanumeric characters
    [[ "${HOST//[0-9A-Za-z_-]/}" = "" ]] || HOST="$DH"
    # Check hostname has no spaces
    [[ -z $HOST ]] && HOST="$DH"
    log "Setting hostname to $HOST"
    hostname $HOST
    hostnamectl set-hostname $HOST
    #nmcli con modify my-office my-office ipv4.dhcp-hostname host-name ipv6.dhcp-hostname host-name
fi

# NOTE: at this point networking is not running, so ifconfig won't work!

# Also set hostname in /etc/hosts (only add if not already present)
   HOSTSFILE="/etc/hosts"
   grep -q " $HOST" $HOSTSFILE || sed -i "s/localhost/& $HOST/" $HOSTSFILE

      # If they chose dynamic (dhcp) then there will be no IP in file
# Resetting Hostname-Setup to not repeat
sed -i "s/^\(AI_HOST\)=\"Y\"/\1=\"N\"/g" $AUTOINST 2>/dev/null
