#!/bin/sh

BASEDIR="$(dirname $0)"
DEVICE="$1"
MOUNTPOINT="$2"
PASSWORD="$3"
KEYFILE="$4"


getRemoteIp ()
{
	ip_address=$(ifconfig eth0 | grep "inet " | awk '{ print $2 }' | cut -d ":" -f 2)
	ip_netmask=$(ifconfig eth0 | grep "inet " | awk '{ print $4 }' | cut -d ":" -f 2)
	remote_ip=$(ipcalc $ip_address/$ip_netmask | grep HostMin | awk '{ print $2}')

	echo $remote_ip
}

sendInfoNotification ()
{
	MESSAGE="$1"
	wget -q -T 3 -t 1 -O /dev/null "http://$(getRemoteIp):8090/message?msgtype=information&text=$MESSAGE"
}

sendErrorNotification ()
{
	MESSAGE="$1"
	wget -q -T 3 -t 1 -O /dev/null "http://$(getRemoteIp):8090/notification?msgtype=critical&text=$MESSAGE"
}


if [ -r "$BASEDIR/truecrypt_config.cfg" ]
then
	. "$BASEDIR/truecrypt_config.cfg"
else
	echo "truecrypt_config.cfg not found" >&2
	exit 1
fi

# make sure to have "/dev/sdb" (not "/dev/sdb1")
#DEVICE="${DEVICE:0:8}" the bash way does not work in dash -.-
DEVICE="$(echo "$DEVICE" | awk '{print substr($1,0,9)}')"

sendInfoNotification "Encrypt device"
if [ -z "$KEYFILE" ]
then
	message="$($tc_cmd -c --non-interactive --quick --filesystem=none --encryption=AES --hash=RIPEMD-160 -p "$PASSWORD" "$DEVICE")"
	result="$?"
else
	message="$($tc_cmd -c --non-interactive --quick --filesystem=none --encryption=AES --hash=RIPEMD-160 -p "$PASSWORD" -k "$KEYFILE" "$DEVICE")"
	result="$?"
fi

	
if [ "$result" != "0" ]
then
	sendErrorNotification "Encryption failed"
	exit 1
fi

sendInfoNotification "Device encrypted"



if [ -z "$KEYFILE" ]
then
	message="$message\n$($tc_cmd --non-interactive --filesystem=none -p "$PASSWORD" "$DEVICE")"
	result="$?"
else
	message="$message\n$($tc_cmd --non-interactive --filesystem=none -p "$PASSWORD" -k "$KEYFILE" "$DEVICE")"
	result="$?"
fi
	
if [ "$result" != "0" ]
then
	exit 1
fi



sendInfoNotification "Create NTFS filesystem on encrypted device"

TC_DEVICE=$(truecrypt -l | awk '{print $3}')

message="$message\n$(mkfs.ntfs --quick "$TC_DEVICE")"
result="$?"

if [ "$result" != "0" ]
then
	sendErrorNotification "Filesystem creation failed"
	exit 1
fi

sendInfoNotification "Filesystem successfully created"

mount "$TC_DEVICE" "$MOUNTPOINT" 

sendInfoNotification "Stick is now initialized"

echo "$message"
exit 0