#!/bin/bash

img=/abuild/target/disk1.img
hba=fileio_0/disk1
loop=/sys/kernel/config/target/loopback
core=/sys/kernel/config/target/core
sec_tpg="secondary_tg_pt_gp"

if [ ! -f ${img} ] ; then
    [ -d ${img%/*} ] || mkdir ${img%/*}
    qemu-img create -f raw ${img} 4G
fi

if [ ! -d ${core}/${hba} ] ; then
    tcm_node --fileio=$hba /abuild/target/disk1.img 4294967296
fi
[ -d ${core}/${hba} ] || exit 1
if [ ! -d ${core}/${hba}/alua/${sec_tpg} ] ; then
    tcm_node --addtgptgp=$hba secondary_tg_pt_gp
fi

for t in ${loop}/naa.*/tpgt_* ; do
    [ -d ${d} ] || continue
    tpgt=${t##*tpgt_}
    if [ "$tpgt" = "0" ] ; then
	nexus0=1
    fi
    if [ "$tpgt" = "1" ] ; then
	nexus1=1
    fi
done
if [ -z "$nexus0" ] ; then
    tcm_loop --createnexus=0
fi

if [ -z "$nexus1" ] ; then
    tcm_loop --createnexus=1
fi

num_naa=0
for d in ${loop}/naa.* ; do
    [ -d ${d} ] || continue
    naa=${d##*/}
    (( num_naa++ )) || true
    for t in ${d}/tpgt_* ; do
	[ -d ${t} ] || continue
	if [ ! -d ${t}/lun/lun_0 ] ; then
	    tpgt=${t##*tpgt_}
	    tcm_loop --addlun=$naa $tpgt 0 $hba || exit 1
	fi
	if [ $tpgt = "1" ] ; then
	    echo secondary_tg_pt_gp > ${t}/lun/lun_0/alua_tg_pt_gp
	fi
    done
done

tcm_node --listtgptgps=fileio_0/disk1
