#!/bin/sh
. /etc/init.d/tc-functions
TMP="/tmp/mkcryptohome.$$"
dialog --title "Create Encrypted File for Home Directory" --menu "Choose Device/partition" 12 40 5 \
   $(awk '/mnt/{printf "%s %s\n",$1,$2}' /etc/fstab|sort -n) \
   2>"$TMP"
RESULT="$?"; ANSWER=`cat $TMP"`;rm "$TMP"
[ "$RESULT" -eq 1 ] && exit 1
DEVICE="$ANSWER"
LOCAL_DEVICE="${DEVICE##/*/}"
[ -z "$LOCAL_DEVICE" ] && exit 1
find_mountpoint "$LOCAL_DEVICE"
if [ -n "$MOUNTPOINT" ]; then
   if [ "$MOUNTED" == "no" ]; then
      mount "$MOUNTPOINT"
   fi
fi
  

AVAILLOOP="$(losetup -f)"
AVAIL="$(df -m /dev/"$LOCAL_DEVICE" | awk '/^\/dev\//{print $4}')"
dialog --inputbox "Please specify the amount of diskspace in megabytes that you want to use as a mountable encrypted home file. Recommended: 256. Free on /dev/"$LOCAL_DEVICE": "$AVAIL" " 8 62 "256" 2>"$TMP"
RESULT="$?"; ANSWER=`cat $TMP"`;rm "$TMP"
[ "$RESULT" -eq 1 ] && exit 1
echo "${GREEN}Creating mountable crypto home file on on /mnt/"$LOCAL_DEVICE".  This may take a while...${NORMAL}"

dd if=/dev/urandom of=/mnt/"$LOCAL_DEVICE"/tchome.aes bs=1000k count="$ANSWER" &&
echo "${GREEN}Please enter your password, it must be at least 20 characters.${NORMAL}"
losetup -T -e AES "$AVAILLOOP" /mnt/"$LOCAL_DEVICE"/tchome.aes &&
echo "${GREEN}Formatting cryptohome file as ext2..${NORMAL}"
mke2fs -m0 -F "$AVAILLOOP" > /dev/null 2>&1 &&
losetup -d "$AVAILLOOP" &&
echo "${GREEN}Done.  Reboot to use encrypted home with the CRYPTOHOME="$LOCAL_DEVICE" option.${NORMAL}"
sleep 5
