#!/bin/bash
#
# Configures the hostname file based on kernel cmdline or user prompt
# Source functions library
. /etc/init.d/functions
. /usr/libexec/ovirt-functions

trap '__st=$?; stop_log; exit $__st' 0
trap 'exit $?' 1 2 13 15

warn() { printf '%s\n' "$*" >&2; }

if ! is_local_storage_configured; then
    warn "Local storage must be configured prior to setting the hostname."
    exit 99
fi

HOSTNAME_FILE="/etc/sysconfig/network"

function set_hostname {
    start_log
    augtool <<EOF
set /files$HOSTNAME_FILE/HOSTNAME "$1"
EOF
    rc=$?
    if [ $rc = 0 ]; then
        /bin/hostname "$1"
        rc=$?
        if [ $rc -eq 0 ]; then /usr/sbin/persist $HOSTNAME_FILE; fi
    fi
    stop_log
    return $rc
}

function remove_hostname {
    start_log
    augtool <<EOF
rm /files$HOSTNAME_FILE/HOSTNAME
EOF
    rc=$?
    stop_log
    return $rc
}

is_valid_hostname () {
    local host=${1}
    local result=1
    if [[ $host =~ ^([a-zA-Z0-9._-]+)$ ]]; then
        result=$?
    fi
    return $result
}

function prompt_user {
  rc=0
  while true; do
    printf "\n"
    read -p "What is the hostname for this node? "

    if [ -n "$REPLY" ]; then
        if ! is_valid_hostname "$REPLY"; then
            printf "\nInvalid Hostname\n"
            continue
        fi
        if set_hostname $REPLY; then
            printf "\nHostname has been set\n"
        else
            printf "\nSetting hostname failed\n"
            rc=1
        fi
    else
        printf "\n"
        ask_yes_or_no "Blank out the hostnames ([Y]es/[N]o)?"
        case $? in
            0)
                if remove_hostname; then
                    printf "\nHostname was removed.\n"
                else
                    printf "\nRemoving hostname failed\n"
                    rc=1
                fi
                ;;
            1)
                printf "\nNo changes made.\n"
                ;;
        esac
    fi
    break
  done
  return $rc
}

# AUTO for auto-install
if [ "$1" = "AUTO" ]; then
    if [ -n "$OVIRT_HOSTNAME" ]; then
        if set_hostname $OVIRT_HOSTNAME; then
            printf "\nHostname has been set\n"
        else
            printf "\nSetting hostname failed\n"
        fi
    else
        printf "\nHostname not provided. Skipping.\n"
    fi
else
    printf "\n\n Hostname Configuration\n\n"
    prompt_user
fi
