# 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

source "$(dirname "${BASH_SOURCE[0]}")/ip_hostname-validation"

DH="hybappliance" # 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"
      if ! is_valid_hostname "$HOST" ; then
         log "hostname: invalid auto-install hostname '$HOST'; using default '$DH'"
         HOST="$DH"
      fi
      hostname "$HOST" >> "$LOG" 2>&1
      hostnamectl set-hostname "$HOST" >> "$LOG" 2>&1
      #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\n[Tab: Switch fields | Enter: Accept | Arrows: Navigate]\n\nDefault: $P1\n" \
          $H1 $W1 "$P1" 2> $tempfile

       k=$?

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

       if [ "$k" -ne 0 ] ; then
          return 1
       fi
       HOST=$(cat $tempfile)
       if ! is_valid_hostname "$HOST" ; then
          $DIALOG --clear --backtitle "$BT" --title "Invalid Hostname" \
             --msgbox "\nPlease enter a valid hostname.\nExample: appliance-node or node-01.example.com\n" $H1 $W1
          continue
       fi
       break
    done
    log "Setting hostname to $HOST"
   hostname "$HOST" >> "$LOG" 2>&1
   hostnamectl set-hostname "$HOST" >> "$LOG" 2>&1
    #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
