# gestion automatique iSCSI

installed=`dpkg -l "open-iscsi*" | grep ii | cut -d ' ' -f 1`

if [ "x$installed" = "x" ];
then
  zenity --question --title "Manager not here" --text="open-iscsi is not installed\nWould you proceed to this now ?"
  if [ $? = 0 ]
  then
    apt-get install -y open-iscsi open-iscsi-utils
  else
    echo "Operation aborted"
  fi
  exit
fi

if [ x$1 = x ];
then
  zenity --error --title "Syntax" --text="You have to give the server (IP or URL)\n or -u to disconnect disks"
  exit
fi

if [ "$1" != "-u" ];
then
  info=`iscsiadm --mode discovery --type sendtargets --portal $1`
  pos=2
  liste=""
  while [ 1 ];
  do
    volume=`echo $info | cut -d ' ' -f $pos`
    if [ "$volume" = "" ]; then break;fi
    list=`echo "$list $volume"`
    pos=`expr $pos + 2`
  done
  
  disk=`zenity --list --title "Choose an iSCSI disk" --column="Target" $list`
  if [ $? != 0 ]; then exit; fi

  session=`iscsiadm -m session | grep $disk`
  if [ "$session" != "" ]; then zenity --error --title "Error" --text="iSCSI disk already connected"; exit;fi

  iscsiadm --mode node --targetname $disk \ --portal $1 --login
  iscsiadm -m session
else
  sion=`iscsiadm -m session`
  if [ "$sion" = "" ]; then zenity --error --title "Error" --text="No connected disk";exit;fi
  sion=`iscsiadm -m session | cut -d ' ' -f 4`

  name=`zenity --list --title "Choose an iSCSI disk" --column="Target" $sion`
  if [ $? != 0 ]; then exit; fi

  iscsiadm -m node -u -T $name
fi
