#!/bin/bash
##
# Make an iSCSI IQN for localhost

set -e

. ${XENSOURCE_INVENTORY}
IQN_CONF=${FIRSTBOOT_DATA_DIR}/iqn.conf
SETIQN=/opt/xensource/bin/xe-set-iscsi-iqn
UPGRADE="false"
[ -r ${FIRSTBOOT_DATA_DIR}/host.conf ] && . ${FIRSTBOOT_DATA_DIR}/host.conf

REVERSE_PY='
import sys
def f(x):
  tmp = x.rstrip().split(".")
  tmp.reverse()
  return ".".join(tmp)
if __name__ == "__main__": print f(sys.argv[1])
'

geniqn() {
    defaultdomain="example.com"
    
    # generate and reverse the hosts DNS domain name
    domain=$(dnsdomainname || true)
    
    if [ "$domain" = "" ] || [ "$domain" = "(none)" ]; then
        echo Warning: no DNS domain name specified, defaulting to ${defaultdomain} >&2
        domain=${defaultdomain}
    fi
    
    revdomain=$(python -c "${REVERSE_PY}" $domain)

    uuid=$(uuidgen | cut -d- -f1)
    date=$(date +"%Y-%m")
    echo "iqn.${date}.${revdomain}:${uuid}"
}

start() {
    [ "$UPGRADE" = true ] && return 0
    # On upgrade, the host param will already be there - reuse it:
    if $XE host-param-get uuid=${INSTALLATION_UUID} param-name=other-config param-key=iscsi_iqn --minimal &>/dev/null ; then
        IQN="$($XE host-param-get uuid=${INSTALLATION_UUID} param-name=other-config param-key=iscsi_iqn --minimal)"
    elif [ -e ${IQN_CONF} ]; then
        source ${IQN_CONF}
    fi

    if [ -z "${IQN}" ]; then
        IQN=$(geniqn)
    fi

    ${SETIQN} "${IQN}"
    echo Set iSCSI IQN: "${IQN}"
    echo IQN=\'"${IQN}"\' >${IQN_CONF}
}

case $1 in
    start)  start ;;
esac
