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

set -e
# To debug upgrade failures
set -x

export FIRSTBOOT_DATA_DIR=/etc/firstboot.d/data
export XENSOURCE_INVENTORY=/etc/xensource-inventory

UPGRADE="false"
[ -r ${FIRSTBOOT_DATA_DIR}/host.conf ] && . ${FIRSTBOOT_DATA_DIR}/host.conf

. ${XENSOURCE_INVENTORY}
IQN_CONF=${FIRSTBOOT_DATA_DIR}/iqn.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=$(python3 -c "${REVERSE_PY}" $domain)

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

# On upgrade, the host param will already be there - reuse it:
IQN_PARAM="$(xe host-param-get uuid=${INSTALLATION_UUID} param-name=iscsi_iqn 2>/dev/null)"
if [ -n "${IQN_PARAM}" ]; then
    IQN="${IQN_PARAM}"
elif xe host-param-get uuid=${INSTALLATION_UUID} param-name=other-config --minimal 2>/dev/null | grep -q "iscsi_iqn:" ; then
    IQN="$(xe host-param-get uuid=${INSTALLATION_UUID} param-name=other-config param-key=iscsi_iqn --minimal)"
elif [ -n "${IQN_CONF}" ] && [ -e "${IQN_CONF}" ]; then
    source "${IQN_CONF}"
fi

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

xe host-param-set uuid=${INSTALLATION_UUID} iscsi_iqn="${IQN}"
echo Set iSCSI IQN: "${IQN}"
echo IQN=\'"${IQN}"\' >${IQN_CONF}


if [ "$UPGRADE" != "true" ]; then
  # Ensure changes are synced to disk
  xe pool-sync-database
fi

touch /var/lib/misc/ran-generate-iscsi-iqn
