#!/bin/bash

source /etc/profile
tempfile=/tmp/iscsi_$$
database=/etc/base/nasdb

ntfs_mount=/usr/bin/ntfs-3g
ntfs_mount_opt="-o rw,noatime,big_writes,async,iocharset=utf8"

exfat_mount=/sbin/mount.exfat-fuse
exfat_mount_opt="-o umask=000,iocharset=utf8,shortname=mixed,quiet,utf8,flush"

vfat_mount=/bin/mount
vfat_mount_opt="-o umask=000,iocharset=utf8,shortname=mixed,quiet,utf8,flush"

hfs_mount=/bin/mount
hfs_mount_opt="-t hfsplus -o force,rw,umask=0,nls=utf8,nodecompose"

ext4_mount=/bin/mount
ext4_mount_opt="-o rw"

searchKey(){
	local string=$1
	local key=$2
	echo "$string" | grep "$key" >/dev/null
	return $?
}

targetAttr(){
	local iName=$1
	local ipadress=""
	local ip=""
	iscsiadm -m node -T $iName -d0 | while read line
	do
		searchKey "$line" "BEGIN RECORD"
		[ $? -eq 0 ] && {
			ipadress=""
			ip=""
		}
		searchKey "$line" "node.discovery_address"
		[ $? -eq 0 ] && {
			ipadress=`echo "$line" | awk -F' = ' '{print $2}'`
		}
		searchKey "$line" "node.discovery_port"
		[ $? -eq 0 ] && {
			ipadress="${ipadress}:`echo "$line" | awk -F' = ' '{print $2}'`"
		}
		searchKey "$line" "node.conn\[0\].address"
		[ $? -eq 0 ] && {
			ip=`echo "$line" | awk -F' = ' '{print $2}'`
		}
		searchKey "$line" "node.conn\[0\].port"
		[ $? -eq 0 ] && {
			ip="${ip}:`echo "$line" | awk -F' = ' '{print $2}'`"
		}
		searchKey "$line" "END RECORD"
		[ $? -eq 0 ] && {
			[ "$ipadress" = "$ip" ] && {
				echo $ipadress
				return 0
			}
		}
	done
	return 1
}

targetStat(){
	local iName=$1
	local ip=$2
	local state=""
	local start=0
	iscsiadm -m session -P3 2>/dev/null > $tempfile
	while read line
	do
		searchKey "$line" "Target: "
		[ $? -eq 0 ] && start=0
		searchKey "$line" "Target: $iName"
		if [ $? -eq 0 ]; then
			start=1
			continue
		fi
		if [ $start -gt 0 ]; then
			searchKey "$line" "Current Portal: $ip"
			[ $? -eq 0 ] && {
				let start=start+1
				continue
			}
			#start log process...
			if [ $start -gt 1 ]; then
				searchKey "$line" "iSCSI Connection State:"
				[ $? -eq 0 ] && {
					state=`echo "$line" | awk -F': ' 'gsub(" ","_",$2) {print $2}'`
					continue
				}
				searchKey "$line" "Channel 00 Id 0 Lun:"
				[ $? -eq 0 ] && {
					local LUNID=`echo "$line" | awk -F': ' '{print $2}'`
					read line #读取下一行
					searchKey "$line" "Attached scsi disk"
					[ $? -eq 0 ] && state="$state,$(echo "$line" | awk '{print $4}'),$LUNID"
				}
			fi
		fi
	done < $tempfile
	rm -f $tempfile
	#stdout the result...
	echo $state
	return 0
}

mountdevice(){
	local iName=$1
	local state=$2
	local disks=(${state//,/ })
	local shortname=${iName##*.}
	unset disks[0]
	local iscsidir=/mnt/iscsi	
	[ ! -d $iscsidir ] && mkdir -m 555 $iscsidir
	for((i=1;i<${#disks[@]};i=i+2))
	do
		local blkname=${disks[$i]}
		local index=${disks[$i+1]}
		local blk=/dev/$blkname
		local partition="${blk}1"
		[ ! -b "$blk" -o ! -b $partition ] && continue
		local mountpath="${iscsidir}/${shortname}-${index}"
		[ ! -d "$mountpath" ] && mkdir -m 555 "$mountpath"
		df | grep $mountpath > /dev/null
		[ $? -eq 0 ] && continue	
		local fs=`blkid $partition -o export | awk -F= '/TYPE/ {print $2}'`
		if [ "$fs" = "ntfs" ]; then 
			${ntfs_mount} ${ntfs_mount_opt} ${partition} "${mountpath}" > /dev/null
		elif [ "$fs" = "vfat" ]; then                                                    
			${vfat_mount} ${vfat_mount_opt} ${partition} "${mountpath}" > /dev/null
		elif [ "$fs" = "exfat" ]; then
			${exfat_mount} ${exfat_mount_opt} ${partition} "${mountpath}" > /dev/null
		elif [ "$fs" = "hfsplus" ]; then
			fsck.hfsplus -f ${partition} >/dev/null
			${hfs_mount} ${hfs_mount_opt} ${partition} "${mountpath}" > /dev/null
		else
			${ext4_mount} ${ext4_mount_opt} ${partition} "${mountpath}" > /dev/null
		fi
		df | grep $mountpath > /dev/null
		[ $? -eq 0 ] && {
			opdatabase "add" "${shortname}-${index}"
		}
	done
}

opdatabase(){
	local act=$1
	local foldername=$2
	local mntpath=/mnt/iscsi/$foldername
	[ -z "$foldername" ] && return 1
	local folderid=`sqlite3 $database "select folder_id from share where foldername='$foldername'"`
	if [ "$act" = "add" ]; then
		[ -z "$folderid" ] && {
			sqlite3 $database "insert into share(foldername,device,mntpath,owner,oplock,hidden,type,description,extend) VALUES('$foldername','iscsi','$mntpath','admin',0,0,'LFS','','')"
		}
	elif [ "$act" = "del" ]; then
		sqlite3 $database "DELETE FROM share WHERE foldername = '$foldername'"
	fi
}

loadconf(){
	local iName=$1
	local shortname=${iName##*.}
	local configfile=/etc/iscsid/.${shortname}.conf
	[ ! -d /etc/iscsid ] && mkdir -m 755 /etc/iscsid
	if [ -f $configfile ]; then
		local user=`awk -F= '/user=/ {print $2}' $configfile`
		[ ! -z "$user" ] && {
			iscsiadm -m node -T ${iName} -o update -n node.session.auth.username -v ${user}
		}
		local pass=`awk -F= '/pass=/ {print $2}' $configfile`
		[ ! -z "$pass" ] && {
			iscsiadm -m node -T ${iName} -o update -n node.session.auth.password -v ${pass}
			iscsiadm -m node -T ${iName} -o update -n node.session.auth.authmethod -v CHAP
		}
		local head=`awk -F= '/head=/ {print $2}' $configfile`
		[ "$head" = "1" ] && {
			iscsiadm -m node -T ${iName} -o update --name=node.conn[0].iscsi.HeaderDigest --value=CRC32C
		}
		local data=`awk -F= '/data=/ {print $2}' $configfile`
		[ "$data" = "1" ] && {
			iscsiadm -m node -T ${iName} -o update --name=node.conn[0].iscsi.DataDigest --value=CRC32C
		}
	fi
}

service_restart(){
	local svrname=$1	
	[ ! -e /etc/sc.d/$svrname ] && return 1
	local state=`service $svrname status`
	echo "$state" | grep "running" >/dev/null
	if [ $? -eq 0 ]; then
		service $svrname restart > /dev/null
	else
		service $svrname start > /dev/null
	fi
	return 0
}

pids=`pidof iscsid`
if [ ! -z "$pids" ]; then
	targetlist=$(iscsiadm --mode node -P1 | awk -F': ' '/Target/ {print $2}')
	for iName in $targetlist
	do
		ipadress=`targetAttr "$iName"`
		state=`targetStat "$iName" "$ipadress"`
		[ -z "$state" ] && {
			loadconf "$iName"
			iscsiadm --mode node --targetname $iName --portal $ipadress --login
			sleep 1
			state=`targetStat "$iName" "$ipadress"`
		}
		[ -z "$state" ] && continue
		mountdevice "$iName" "$state"
		sleep 1
	done
	df | grep /mnt/iscsi/ >/dev/null
	[ $? -eq 0 ] && {
		svrcfg-all
		service_restart samba
		service_restart ftp
		service_restart nfs
		service_restart afp #afp
	}
else
	smb_status=`ps -ef | grep smbd | grep -v grep | wc -l`
	ftp_status=`ps -ef | grep smbftpd | grep -v grep | wc -l`
	nfs_status=`ps -ef | grep nfsd | grep -v grep | wc -l`
	afp_status=`ps -ef | grep netatalk | grep -v grep | wc -l`
	# stop the iscsid
	[ $smb_status -gt 0 ] && service samba stop
	[ $ftp_status -gt 0 ] && service ftp stop
	[ $nfs_status -gt 0 ] && service nfs stop
	[ $afp_status -gt 0 ] && service afp stop
	df -P | awk '/\/mnt\/iscsi/ {print $6}' | while read line
	do
		umount $line
		[ -d $line ] && rm -fr $line
		foldername=$(basename "$line")
		[ ! -z "$foldername" ] && rm -f /mnt/$foldername
		opdatabase "del" "${foldername}"
	done
	svrcfg-all
	[ $smb_status -gt 0 ] && service samba start
	[ $ftp_status -gt 0 ] && service ftp start
	[ $nfs_status -gt 0 ] && service nfs start
	[ $afp_status -gt 0 ] && service afp start
fi
