#! /bin/bash

export PATH=/sbin:/usr/sbin:/bin:/usr/bin

params=
echo "Loading scsi_mod"
modprobe scsi_mod $params

echo "Loading sd_mod"
modprobe sd_mod $params

echo "Loading scsi_transport_iscsi"
modprobe scsi_transport_iscsi $params

echo "Loading libiscsi"
modprobe libiscsi $params

echo "Loading iscsi_tcp"
modprobe iscsi_tcp $params

function configure_network()
{
netconfig="\
    <interfaces config:type=\"list\">
      <interface>
        <bootproto>static</bootproto>
        <device>$interface</device>
        <ipaddr>$initiatorip</ipaddr>
        <netmask>$netmask</netmask>
        <startmode>nfsroot</startmode>
        <usercontrol>no</usercontrol>
      </interface>
    </interfaces>\
"
	cat /tmp/profile/autoinst.xml | awk '
		$0 ~ /NETWORK_CONFIGURATION/ && $0 !~ /sub/ { sub("NETWORK_CONFIGURATION", netconfig); }
		{ print $0; }
	' netconfig="$netconfig" > /tmp/profile/modified.xml	
}

iscsi_verify_params()
{
	# Open/read the file created by gettargetparams
	# Case statement to set actual target variables

	local left=
	local right=

	while read line ;do
	if [ ! -z "$line" ];then
		left=`echo $line | sed 's/\(.*\)=.*/\1/'`
		right=`echo $line | sed 's/.*=\(.*\)/\1/'`

		if [ "$left" = "TargetName" ];then
			iscsitarget=$right;
		fi

		if [ "$left" = "InitiatorName" ];then
			echo "InitiatorName=$right" > /etc/initiatorname.iscsi
			# iscsid on some ditro expect initiatorname.iscsi file
			# to be present under /etc/iscsi directory
			mkdir -p /etc/iscsi
			echo "InitiatorName=$right" > /etc/iscsi/initiatorname.iscsi
		fi

		if [ "$left" = "TargetIP" ];then
			iscsiserver=$right;
		fi

		if [ "$left" = "TargetPort" ];then
			iscsiport=$right;
		fi

		if [ "$left" = "InitiatorIP" ];then
			initiatorip=$right;
		fi

		if [ "$left" = "InitiatorNetmask" ];then
			netmask=$right;
		fi

		if [ "$left" = "InitiatorRoute" ];then
			route=$right;
		fi

		if [ "$left" = "LAA" ];then
			laa=$right;
		fi

		if [ "$left" = "VLAN" ];then
			if [ "$right" = "Disabled" ];then
				vlan=0;
			else
				vlan=$right;
			fi
		fi

		if [ "$left" = "LUN" ];then
			lun_number=$right;
		fi

		if [ "$left" = "AuthMethod" ];then
			authmethod=$right;
		fi

		if [ "$left" = "CHAPUsername" ];then
			chapuser=$right;
		fi

		if [ "$left" = "CHAPSecret" ];then
			chapsecret=$right;
		fi

		if [ "$left" = "CHAPMSecret" ];then
			chapmsecret=$right;
		fi

		if [ "$left" = "BusInfo" ];then
			pciinfo=$right;
		fi

	fi
	done < /tmp/conf_file
}

# Before loading network driver, obtain iSCSI parameters left by option ROM.
# This is vendor-specific.

echo "Reading iscsi configuration"
./get_iscsi_conf > /tmp/conf_file
if [ $? -ne 0 ]
then
	echo "Error: Failed to read iscsi configuration"
	cat /tmp/conf_file
	exit 1
fi

# Verify the target parameters
iscsi_verify_params

# The variables initiatorip, vlan, laa, netmask, and route need to
# be verified and used to bring up the network interface.
# Input to ipconfig:
#  <clientip>:<serverip>:<gw-ip>:<netmask>:<hostname>:<device>:<autoconf>
# TODO: Setting the MAC address using LAA is not yet supported
# TODO: Vlans are not yet supported
# TODO: DHCP mode for target IP is not yet supported
# TODO: add DHCP support for initiatorip (in mkinitrd)

echo "Loading bnx2"
modprobe bnx2 $params

# Always enable DHCP for iSCSI
dhcp_mode=1

# Use pci, device, and function to obtain proper interface to bring up

./get_interface $pciinfo > /tmp/interface

for o in $(cat /tmp/interface); do
  interface=$o
done
if [ -z "$interface" ]; then
  interface=eth0
fi
if [ -n "$initiatorip" ]; then
  ifspec=$initiatorip::$route:$netmask::$interface:
fi

if [ -z "$ifspec" ]; then
    # Fallback to configured interface
    #ifspec=10.10.10.164:::.0.0.0.0:10.10.10.164:eth0:none
    # Needs to look like:
    echo "Warning: falling back to configured interface!!!"

    ifspec=10.10.10.164:::netmask::eth0:none
fi
if [ -n "$ifspec" ]; then
  if [ -f /bin/ipconfig ];then
	  /bin/ipconfig $ifspec
  else
  	/sbin/ifconfig $interface $initiatorip netmask $netmask up
  fi
#configure_network
fi
#end of new code
iscsi_login_root_node()
{

# For install, we start with discovery, then probe the db for the proper entry.

    local iscsi_sid

    if [ -z "$iscsi_sid" ] ; then
        # Use discovery to add correct target
        if [ -n "$iscsiserver" ] ; then 
	  echo "Target NOT found. Using discovery to find target"
          /sbin/iscsiadm -m discovery -t sendtargets -p $iscsiserver >/dev/null
	  echo "Scanning database"
          # scan database
          if [ -n "$iscsitarget" ] ; then 
            if [ -n "$iscsiserver" ] ; then 
              if [ -n "$iscsiport" ] ; then 
              iscsi_sid=$(/sbin/iscsiadm -m node | grep $iscsitarget | grep $iscsiserver | grep $iscsiport | sed 's@\[\(.*\)\] .*@\1@g')
              else
              iscsi_sid=$(/sbin/iscsiadm -m node | grep $iscsitarget | grep $iscsiserver | sed 's@\[\(.*\)\] .*@\1@g')
              fi
            else
              iscsi_sid=$(/sbin/iscsiadm -m node | grep $iscsitarget | sed 's@\[\(.*\)\] .*@\1@g')
            fi
          else
            if [ -n "$iscsiserver" ] ; then 
              iscsi_sid=$(/sbin/iscsiadm -m node | grep $iscsiserver | sed 's@\[\(.*\)\] .*@\1@g')
            fi
          fi
        fi
    fi

    if [ -z "$iscsi_sid" ] ; then
      echo "Error: Unable to determine target from option ROM data, exiting"
      exit 1
    fi

    # For CHAP, need to add login parameters via iscsiadm before attempting to
    # login. Ignore Mutual CHAP until we get a login name from the option ROM.

    if [ $authmethod != "None"  ]; then
      echo "setting CHAP parameters"
      /sbin/iscsiadm -m node -r $iscsi_sid -o update -n node.session.auth.authmethod -v CHAP
      /sbin/iscsiadm -m node -r $iscsi_sid -o update -n node.session.auth.username -v $chapuser
      /sbin/iscsiadm -m node -r $iscsi_sid -o update -n node.session.auth.password -v $chapsecret
    fi

    echo -n "Logging into $iscsitarget: "
    if /sbin/iscsiadm -m node -r $iscsi_sid -l ; then
	echo "ok."
    else
	echo "failed."
	exit 1
    fi
}

# If Authmethod is CHAP, then add discovery.sendtargets data to /etc/iscsid.conf
# in case target is not yet in database. Ignore Mutual CHAP support for now.
# The option ROM must return us a login name for Mutual CHAP to be supported.
# Currently, it only passes the password(secret).
if [ $authmethod != "None"  ]; then
    echo "discovery.sendtargets.auth.authmethod = CHAP" >/etc/iscsid.conf
    echo "discovery.sendtargets.auth.username = $chapuser" >>/etc/iscsid.conf
    echo "discovery.sendtargets.auth.password = $chapsecret" >>/etc/iscsid.conf
fi

echo "Starting iSCSI daemon"
/sbin/iscsid
usleep 5000000

# Login to the root node
iscsi_login_root_node

# allow the disk to come up fully
usleep 5000000
usleep 5000000

disk=`./get_iscsi_disk $iscsitarget $lun_number`
if [ $? -ne 0 ]
then
	exit 1
fi
echo "Found Disk: $disk"
cat /tmp/profile/autoinst.xml | awk '
	$0 ~ /ISCSI_DISK/ && $0 !~ /sub/ { sub("ISCSI_DISK", disk); }
	{ print $0; }
' disk="$disk" > /tmp/profile/modified.xml	

exit 0
