#!/bin/sh
#
# Copyright (C) Citrix Systems Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation; version 2.1 only.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

SCRIPT=$(basename $0)
TMPDIR=$(mktemp --tmpdir -d $SCRIPT.XXXXXXXXX)
cleanup() {
    if [ -n "$TMPDIR" ]; then
        rm -rf "$TMPDIR"
    fi
}
ecleanup() {
    cleanup
    exit 1
}
trap cleanup EXIT
trap ecleanup INT
trap ecleanup TERM

mkdir -p /var/lock/sm/iscsiadm

INITIATORFILE=/etc/iscsi/initiatorname.iscsi
RUNNING_LOCK=/run/lock/sm/iscsiadm/running

INITIATORNAME=$1
INITIATORALIAS=$2

# Ensure the lock is created
mkdir -p $(dirname $RUNNING_LOCK)
touch $RUNNING_LOCK

(
        flock -s 200

        CURRENT_INITATOR=$(awk 'BEGIN { FS = "=" } /InitiatorName/ {print $2}' $INITIATORFILE)

        # Only care that the initiator name is the name, alias may be missing
        if [ "$CURRENT_INITATOR" == "$INITIATORNAME" ]
        then
            exit 0
        fi

        iscsiadm -m session > /dev/null 2>&1
        if [ $? -eq 0 ]
        then
                logger -p local2.err "set-iscsi-initiator active sessions so not updating"
                echo "set-iscsi-initiator: there are active sessions so not updating" >&2
                exit 1
        fi

        echo "InitiatorName=$INITIATORNAME" > $INITIATORFILE
        echo "InitiatorAlias=$INITIATORALIAS" >> $INITIATORFILE

        systemctl is-active -q iscsid.service
        if [ $? -eq 0 ]
        then
            # iscsid is running so restart
            systemctl restart iscsid.service
        fi

) 200>$RUNNING_LOCK
