#!/bin/bash

function usage() {
	echo "Usage: `basename $0` <action> SRC DEST"
	echo "Example:"
	echo "  uricmd [--hicomimg <imgfile>] rmxvzcopy :a1h1e: V6_R1.11.0.zip"
	echo "  uricmd [--hicomimg <imgfile>] rmxcopy :PDS:/APSP/LTG/LGA0/PZKSGW50 /.AS/sglw"
	echo " "
	exit 1
}

[ $1 == "--hicomimg" -a -f $2 ] && {
	realfile=$2
	shift 2
}


usedprog="$1"

[ -z "$3" ] && usage

case "$1" in
	rmxvzcopy)
		true
		;;
	rmxcopy)
		true
		;;
	*)
		usage
		;;
esac

[ -z "$realfile" ] && {
	[ ! -f /opt/dscxl/share/hicom.img ] && {
	echo "File /opt/dscxl/share/hicom.img does not exist. Make the hicom.img link first."
	exit 1
}
realfile=`ls -l /opt/dscxl/share/hicom.img | awk '{print $NF}'`
}
echo "Checking if some other process is accessing the rmx image ..."
lsof -n 2>&1 | grep -q $realfile && {
	echo "ERROR: Real file $realfile is being used by the above processes. This may lead to corruptions and is not allowed."
	exit 1
}

#make sure RMX HD is deactivated
python -c "exec(\"fo=open('$realfile','rb+')\n"\
"fo.seek(0x398,0)\n"\
"for x in range(1,8):\n"\
"\tfo.seek(0x1f,1)\n"\
"\tfo.write(bytearray([0]))\n"\
"fo.close()\n\")"

losetup -a | grep $realfile || {
	loopdev=`losetup --show -f $realfile`
	[ -z "$loopdev" ] && {
		echo "ERROR: loop device on $realfile not created."
		exit 1
	}
}

mkdir -p /tmp/tooltmp
rm -f /tmp/tooltmp/hicom
ln -s $loopdev /tmp/tooltmp/hicom

echo "Doing the $* ..."
export PATH=`pwd`:${0%/*}/:$PATH
$*
result=$?

for i in {0..10}; do
  losetup -d $loopdev
  if losetup -a | grep $realfile; then
    echo "WARNING: loop device to $realfile still in use."
    sleep 6
  else
    break
  fi
done

echo "Result of $1 was : $result"
[ $result -ne 0 ] && echo "Failed."
exit $result
