#!/bin/sh
# postinst script for xvm-iscsi-config
#
# see: dh_installdeb(1)

set -e

# Source debconf library
. /usr/share/debconf/confmodule

# summary of how this script can be called:
#        * <postinst> `configure' <most-recently-configured-version>
#        * <old-postinst> `abort-upgrade' <new version>
#        * <conflictor's-postinst> `abort-remove' `in-favour' <package>
#          <new-version>
#        * <postinst> `abort-remove'
#        * <deconfigured's-postinst> `abort-deconfigure' `in-favour'
#          <failed-install-package> <version> `removing'
#          <conflicting-package> <version>
# for details, see http://www.debian.org/doc/debian-policy/ or
# the debian-policy package

# dh_installdeb will replace this with shell code automatically
# generated by other debhelper scripts.

#DEBHELPER#

case "$1" in
    configure)
        db_get xvm-iscsi-config/address
        ADDRESS="$RET"
        db_get xvm-iscsi-config/username
        USERNAME="$RET"
        db_get xvm-iscsi-config/password
        PASSWORD="$RET"
        db_stop
        
        if [ -e /etc/invirt/conf.d/iscsi ]; then
          # invirt.config.run_parts_list excludes backup filenames.
          mv -f /etc/invirt/conf.d/iscsi /etc/invirt/conf.d/iscsi~
        fi
        cat >/etc/invirt/conf.d/iscsi <<EOF
iscsi:
 address: $ADDRESS
 username: $USERNAME
 password: $PASSWORD
EOF
        if [ -z "$2" ]; then
            invoke-rc.d xvm-iscsi-config restart
            invoke-rc.d open-iscsi restart
            iscsiadm -m discovery -t st -p $(invirt-getconf iscsi.address):3260 -I eth0 -I eth1
        elif ! diff /etc/invirt/conf.d/iscsi~ /etc/invirt/conf.d/iscsi >/dev/null; then
              cat <<EOF
xvm-iscsi-config: The configuration has changed.  Restart iscsi:
  /etc/init.d/xvm-iscsi-config restart
  /etc/init.d/open-iscsi restart
  iscsiadm -m discovery -t st -p $(invirt-getconf iscsi.address):3260 -I eth0 -I eth1
  lvchange -a ln /dev/xenvg && lvchange -a y /dev/xenvg
This will leave VMs unable to access their disks, so migrate them first.

EOF
        fi
    ;;

    abort-upgrade|abort-remove|abort-deconfigure)
    ;;

    *)
        echo "postinst called with unknown argument \`$1'" >&2
        exit 1
    ;;
esac

exit 0