# Mount encryped shared folders
# Original author:  Twisted World, JasonP, Volterra
# Original source:  https://forum.synology.com/enu/viewtopic.php?f=36&t=142308
# Repository:       https://github.com/volterra4/synologyshareautomount
# Author:           bco, 2019-02-11, 2019-03-26, 2019-05-07, 2020-04-28
#
debian=0 # set to 1 for a debian host, 0 for a synology host
debug=0  # set to 1 to check encryption without mounting volumes
if [ "$#" -ne 7 ]; then
	script=`basename $0`
	echo "Usage: ./$script <url> <vol> <share> <pass> <host> <try_delay> <try_count>"
	echo "---"
	echo "<url> is the url towards which the wget command is executed"
	echo "<vol> is the name of the volume the share resides on"
	echo "<share> is the name of the encrypted share to be mounted"
	echo "<pass> is the password used to decrypt the password coming from the web server"
	echo "<host> must be either ip or hostname used to check internet connection availability through a ping"
	echo "<try_delay> is the wait period (in seconds) between adjacent tries"
	echo "<try_count> specifies the maximum number of tries before giving up"
	echo "--- must be run as root"
else
	# assign arguments to named variables
	url=$1
	vol=$2
	share=$3
	pass=$4
	host=$5
	delay=$6 # try_delay
	count=$7 # try_count
	query="/html/synology.php"

	echo "[$(date)] - Started automatic share mounter"
	echo "[$(date)] - Time delay between each try $delay seconds"
	echo "[$(date)] - Will try up to $count times"
	while [[ $count -ne 0 ]] ; do
		sleep $delay
		ping -c 1 $host > /dev/null 2>&1
		if [[ $? -eq 0 ]] ; then
			echo "[$(date)] - Key server is online"
			cryptpass=$(wget -nv -O - $url$query?$vol-$share -q)
			if [ "$cryptpass" == "" ]; then
				cryptpass=$(ssh bco@$host -i /volume1/homes/bco/.ssh/id_rsa "wget -nv -O - 127.0.0.1$query?$vol-$share -q")
			fi
			if [[ "$cryptpass" != "" ]]; then
				password=$(echo "$cryptpass" | openssl enc -aes-256-cbc -a -d -salt -pass pass:$pass)
				echo "[$(date)] - Mounting the encrypted share: $share on $vol"

				if [[ "$debug" == "1" ]]; then
					# testing
					echo -e "[$(date)] - Encrypted key=$cryptpass\n[$(date)] - Decrypted key=$password"
				else
					# production
					if [[ "$debian" == "1" ]]; then
						result=$(echo $password | cryptsetup luksOpen /dev/mapper/$vol $vol"_crypt")
						result2=$(mount /dev/mapper/$vol"_crypt" /$share)
					else
						result=$(synoshare --enc_mount $share $password)
					fi
				fi

				if [[ $? -eq 0 ]]; then
					password=""
					echo "[$(date)] - Mount succesful!"
					count=1
				else
					echo "[$(date)] - Mount error #$result"
				fi
			fi
		fi
		count=$count-1
	done
	echo ""
fi
exit 0
