#!/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 iSCSI Initiator Name."
    exit 99
fi

INITIATOR_FILE="/etc/iscsi/initiatorname.iscsi"

function prompt_user {
    printf "\n"
    printf "Enter iSCSI Initiator Name (If blank one will be automatically generated)\n"
    printf "Enter Q to quit\n"
    read REPLY
    if [[ $REPLY == "q" || $REPLY == "Q" ]]; then
        printf "Aborting due to user request"
        return
    fi

    set_initiator $REPLY
}

function set_initiator {
    if [ -z "$1" ]; then
        INITIATOR_NAME=$(iscsi-iname)
    else
        INITIATOR_NAME=$1
    fi

    echo "InitiatorName=$INITIATOR_NAME" > $INITIATOR_FILE
    ovirt_store_config $INITIATOR_FILE
    rc=$?
    if [ $rc = 0 ]; then
        printf "Initiator name set as: $INITIATOR_NAME\n"
    else
        printf "Setting initiator name failed\n"
    fi
}

# AUTO for auto-install
if [ "$1" = "AUTO" ]; then
    set_initiator $OVIRT_ISCSI_NAME
else
    printf "\n\n iSCSI Initiator Configuration\n\n"
    prompt_user
fi
