Target export device script

#!/bin/sh## This script illustrates the sequence of operations in configfs to# create a very simple LIO iSCSI target with a file or block device# backstore.## (C) Copyright 2014 Christophe Vu-Brugier <cvubrugier@fastmail.fm>#print_usage(){cat<<EOFUsage: $(basename $0) [-p PORTAL] DEVICE|FILEExport a block device or a file as an iSCSI target with a single LUNEOF}die(){echo$1exit1}whilegetopts"hp:"arg;docase$arginh)print_usage;exit0;;p)PORTAL=${OPTARG};;esacdoneshift$(($OPTIND-1))DEVICE=$1[-n"$DEVICE"]||die"Missing device or file argument"[-b$DEVICE-o-f$DEVICE]||die"Invalid device or file:${DEVICE}"IQN="iqn.2003-01.org.linux-iscsi.$(hostname):$(basename$DEVICE)"[-n"$PORTAL"]||PORTAL="0.0.0.0:3260"CONFIGFS=/sys/kernel/configCORE_DIR=$CONFIGFS/target/coreISCSI_DIR=$CONFIGFS/target/iscsi# Load the target modules and mount the config file systemlsmod|grep-qconfigfs||modprobeconfigfslsmod|grep-qtarget_core_mod||modprobetarget_core_modmount|grep-q^configfs||mount-tconfigfsnone$CONFIGFSmkdir-p$ISCSI_DIR# Create a backstoreif[-b$DEVICE];thenBACKSTORE_DIR=$CORE_DIR/iblock_0/datamkdir-p$BACKSTORE_DIRecho"udev_path=${DEVICE}">$BACKSTORE_DIR/controlelseBACKSTORE_DIR=$CORE_DIR/fileio_0/datamkdir-p$BACKSTORE_DIRDEVICE_SIZE=$(du-b$DEVICE|cut-f1)echo"fd_dev_name=${DEVICE}">$BACKSTORE_DIR/controlecho"fd_dev_size=${DEVICE_SIZE}">$BACKSTORE_DIR/controlecho1>$BACKSTORE_DIR/attrib/emulate_write_cachefiecho1>$BACKSTORE_DIR/enable# Create an iSCSI target and a target portal group (TPG)mkdir$ISCSI_DIR/$IQNmkdir$ISCSI_DIR/$IQN/tpgt_1/# Create a LUNmkdir$ISCSI_DIR/$IQN/tpgt_1/lun/lun_0ln-s$BACKSTORE_DIR$ISCSI_DIR/$IQN/tpgt_1/lun/lun_0/dataecho1>$ISCSI_DIR/$IQN/tpgt_1/enable# Create a network portalmkdir$ISCSI_DIR/$IQN/tpgt_1/np/$PORTAL# Disable authenticationecho0>$ISCSI_DIR/$IQN/tpgt_1/attrib/authenticationecho1>$ISCSI_DIR/$IQN/tpgt_1/attrib/generate_node_acls# Allow write access for non authenticated initiatorsecho0>$ISCSI_DIR/$IQN/tpgt_1/attrib/demo_mode_write_protectecho"Target${IQN}, portal${PORTAL} has been created"