#!/bin/sh
#
# $NetBSD: iscsid_volumes,v 1.5 2023/12/25 08:29:05 kre Exp $
#

# PROVIDE: iscsid_volumes
# REQUIRE: iscsid
# BEFORE:  securelevel mountcritremote

$_rc_subr_loaded . /etc/rc.subr

name="iscsid_volumes"
rcvar=$name
start_cmd="iscsid_volumes_start"
stop_cmd="iscsid_volumes_stop"

iscsid_volumes_start()
{
	test -f /etc/iscsi/volumes || return 0

	while read host target digest auth user alias; do
		case $host in
		\#*|"") ;;
		*)
			topts=''
			case $digest in
			*d*) topts="$topts -d";;
			esac
			case $digest in
			*h*) topts="$topts -h";;
			esac

			pass="-"
			mpass="-"

			if [ -f /etc/iscsi/auths ]; then
				while read entry dummy; do

					case $entry in
					*:chap:*|\
					*:CHAP:*|\
					*:none:*)
						dummy=${entry#*:}
						entry=${entry%%:*}:${dummy#*:}
						;;
					esac

					case $entry in
					\#*|"") ;;
					"$user":*) pass=${entry#*:} ;;
					"$target":*) mpass=${entry#*:} ;;
					esac
				done < /etc/iscsi/auths
			fi

			case $host in
			*:*)
				port=${host#*:}
				host=${host%%:*}
				;;
			*)
				port=3260
				;;
			esac

			echo "Add target ${alias:-$target}"

			out=$(/sbin/iscsictl add_target$topts \
				-a "$host" \
				-p "$port" \
				-n "$target" \
				-t "$auth" \
				-u "$user" \
				-s "$pass" \
				-S "$mpass" \
				${alias:+-N} ${alias:+"$alias"})
			echo "$out"

			case $out in
			Added\ Target\ [1-9]*,\ Portal\ [1-9]*\ )
				out=${out% }
				portal=${out##* }
				echo "Login $target via Portal $portal"
				/sbin/iscsictl login -P "$portal"
				;;
			esac
		esac
	done < /etc/iscsi/volumes
}

iscsid_volumes_stop()
{
	test -f /etc/iscsi/volumes || return 0

	while read host target digest auth user alias; do
		case $host in
		\#*|"") ;;
		*)
			echo "Remove target ${alias:-$target}"

			/sbin/iscsictl list_sessions |
			    while read key1 num key2 sesstarget; do
				if [ x"$key1" = x"Session" ] &&
				   [ x"$key2" = x"Target"  ] &&
				   [ x"$sesstarget" = x"$target" ]
				then
					/sbin/iscsictl logout -I "$num" |
					    grep -v '^OK$'
				fi
			done

			/sbin/iscsictl list_targets |
			    while read num talias ttarget; do
				if [ x"$ttarget" = x"$target" ]; then
					/sbin/iscsictl remove_target -I "$num"
				fi
			done
			;;
		esac
	done < /etc/iscsi/volumes
}

load_rc_config $name
run_rc_command "$1"
