#!/bin/bash

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
cMount=0
#open map
isMapMount=`mount | grep /home/jetson/map`
if [ "$isMapMount" = "" ]; then
    echo "Start mount map" > ${resultLog}
    while true
    do
	echo ${Pass} | cryptsetup --readonly open /home/jetson/mec my_enc_mec
	resCrypto=$?
	echo "Crypt result: ${resCrypto}" >> ${resultLog}
	if [ ${resCrypto} -ne 0 ]; then 
	    sleep 1
	    cryptsetup close my_enc_mec
	    echo "Crypt close result: $?" >> ${resultLog}
	    sleep 4
	    continue
	fi
	
	sleep 1
	mkdir ${point}
	
	mount -o ro /dev/mapper/my_enc_mec ${point}
	resMount=$?
	echo "Mount result: ${resMount}" >> ${resultLog}
	if [ ${resMount} -ne 0 ]; then 
	    sleep 1
	    umount -l ${point}
	    echo "Umount result: $?" >> ${resultLog}
	    sleep 1
	    cryptsetup close my_enc_mec
	    echo "Crypt close result: $?" >> ${resultLog}
	    sleep 3
	else
	    break
	fi
	if [ "$cMount" -eq 5 ]; then
	    echo "Error mount map!!!!" >> ${resultLog}
	    break
	fi
	cMount=`expr $cMount + 1`
    done
fi

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

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

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

    echo $Pass | gpg --yes --batch --passphrase-fd 0 --output /home/jetson/thunder_gaze/thunder_gaze_f1.tgz --no-symkey-cache /home/jetson/ThunderGaze.gpg

    cd /home/jetson/thunder_gaze
    tar zxvf /home/jetson/thunder_gaze/thunder_gaze_f1.tgz

    rm -f /home/jetson/thunder_gaze/thunder_gaze_f1.tgz
fi


