#!/bin/bash

read -r pass
#pass=$1
point="/home/jetson/map"
resultLog="/home/jetson/resultMapOpen"

COUNT=$(ps ax | grep -w $(basename "$0") | grep -v "grep" | grep -v "$$" | wc -l)
echo $COUNT
if [ "$COUNT" -gt 1 ]; then
    echo "Script is already running..."
    exit 1
fi

function mountCrypt {
    mkdir ${point}
    echo ${pass} | cryptsetup --readonly open /home/jetson/mec my_enc_mec
    echo "Crypt result: $?" >> ${resultLog}
    sleep 3
    mount -o ro /dev/mapper/my_enc_mec ${point}
    echo "Mount result: $?" >> ${resultLog}
}
function umountCrypt {
    umount -l ${point}
    echo "UMount result: $?" >> ${resultLog}
    sleep 3
    cryptsetup close my_enc_mec
    echo "Crypt close result: $?" >> ${resultLog}
}


#open map
isMapMount=`mount | grep /home/jetson/map`
if [ "$isMapMount" = "" ]; then
    echo "Start mount map" > ${resultLog}
    cMount=0
    while true
    do

	if [ "$cMount" -eq 5 ]; then
	    echo "Error mount map!!!!" >> ${resultLog}
	    break
	fi
	cMount=`expr $cMount + 1`

	mountCrypt
	sleep 5

	sMec=`ls -s /home/jetson/mec | awk '{print $1}'`
	sFolder=`du -s ${point} | awk '{print $1}'`
	if [ $(($sMec/2)) -gt $sFolder ]; then 
	    echo "Mount error!!!! Retry." >> ${resultLog}
	    umountCrypt
	    sleep 5
	    continue
	else
	    echo "Map ready!" >> ${resultLog}
	    break
	fi
    done
fi

#open tg
thg="/home/jetson/thunder_gaze"

isTGMount=`mount | grep /home/jetson/thunder_gaze`
if [ "$isTGMount" = "" ]; then

    #sizeTG=`du -m /home/jetson/ThunderGaze.gpg | awk '{print $1}'`
    #sizeTG="$((($sizeTG + 20)*2))"

    mkdir ${thg}
    mount -t ramfs ramfs ${thg}
    #mount -t tmpfs -o size=${sizeTG}M tmpfs /home/jetson/thunder_gaze

    echo $pass | gpg --yes --batch --passphrase-fd 0 --output ${thg}/thunder_gaze_f1.tgz --no-symkey-cache ${thg}/../ThunderGaze.gpg

    cd ${thg}
    tar zxvf ${thg}/thunder_gaze_f1.tgz

    rm -f ${thg}/thunder_gaze_f1.tgz
fi
