#!/bin/bash

#set -xv

LANG=en_US.UTF-8
export LANG

. /etc/profile

eval `cat /proc/cmdline | sed -e 's|\s|\n|g' | grep ^TC`

if [ ! -f /storage/.kodi/userdata/.truecrypt_mounted -a -b /dev/${TCdev##*/} ] ; then
	if [ ! -f /tmp/foobar.${TCdev##*/} ] ; then
		/storage/.truecrypt/get-pw.sh || exit 1
	fi
	if [ -f /tmp/foobar.${TCdev##*/} ] ; then
		systemctl status kodi.service >/dev/null
		if [ $? -eq 0 ] ; then
			systemctl stop kodi.service
			echo "kodi is running ... stoping now"
			START=1
		fi
		echo -e "mounting userdata ...\c"
		/storage/.kodi/addons/plugin.program.truecrypt/bin/truecrypt.sh mount ${TCdev} /storage/.kodi/userdata "" /tmp/foobar.${TCdev##*/} 2>/dev/null
		echo " done"
		rm /tmp/foobar.${TCdev##*/}
		if [ -f /storage/.kodi/userdata/.truecrypt_mounted ] ; then
			echo "${TCdev} mounted to /storage/.kodi/userdata/"
		fi
		if [ $START -eq 1 ] ; then
			echo "kodi was running ... starting now"
			systemctl start kodi.service
		fi
	fi
fi
rm -f /tmp/foobar.${TCdev##*/} 2>/dev/null

for color in red blue yellow green black silver white ; do
	if [ ! -f /var/media/${color}/.truecrypt_mounted -a -b /dev/disk/by-partlabel/${color} ] ; then
		if [ ! -f /tmp/foobar.${color} ] ; then
			/storage/.truecrypt/get-pw.sh || exit 1
		fi
		if [ -f /tmp/foobar.${color} ] ; then
			if [ ! -d /var/media/${color} ] ; then
				mkdir /var/media/${color}
			fi
			echo -e "mounting ${color} ...\c"
			/storage/.kodi/addons/plugin.program.truecrypt/bin/truecrypt.sh mount /dev/disk/by-partlabel/${color} /var/media/${color} "" /tmp/foobar.${color} 2>/dev/null
			echo " done"
			rm -f /tmp/foobar.${color} 2>/dev/null
			if [ -f /var/media/${color}/.truecrypt_mounted ] ; then
				echo "${color} mounted to /var/media/${color}"
				if [ -d /var/media/${color}/.rsync ] ; then
					echo "starting rsync backup"
					/storage/.rsync/kodi.rsync.sh
				fi
			fi
		fi
	fi
	rm -f /tmp/foobar.${color} 2>/dev/null
done

