#!/bin/sh

# Part of passwordless cryptofs setup in Debian Etch.
# See: http://wejn.org/how-to-make-passwordless-cryptsetup.html
# Author: Wejn <wejn at box dot cz>
#
# Updated by Rodolfo Garcia (kix) <kix at kix dot com>
# For multiple partitions
# http://www.kix.es/
#
# Updated by Cromwel Flores <cromwel dot flores at gmail dot com>
# For MMC/SD card

# Disk partition type (ext2 or vfat)
PARTTYPE=vfat
# Key file in the disk
KEYFILE=root.key

# # # # # CODE # # # # #
MD=/tmp-mount

if [ "x$1" = "x" -o "x$1" = "xnone" ]; then
    KEYF=$KEYFILE
else
    KEYF=$1
fi

USBLOAD=0
FSLOAD=0
MMCLOAD=0
cat /proc/modules | busybox grep usb_storage >/dev/null 2>&1
USBLOAD=$?
cat /proc/modules | busybox grep $PARTTYPE >/dev/null 2>&1
FSLOAD=$?
cat /proc/modules | busybox grep mmc >/dev/null 2>&1
MMCLOAD=$?

#Check if all the required modules have been already loaded
if [ $USBLOAD -gt 0 ] || [ $FSLOAD -gt 0 ] || [ $MMCLOAD -gt 0 ]; then
    modprobe usb_storage
    modprobe mmc_core
    modprobe ricoh_mmc
    modprobe mmc_block
    modprobe sdhci
    modprobe $PARTTYPE
fi

OPENED=0

ls -d /sys/block/sd* >/dev/null 2>&1
SDS=$?

if [ $SDS -eq 0 ]; then
    echo "Trying to get the keyfile from physical keychain ..." >&2
    mkdir -p $MD

# Try getting file from SD Card
    echo "> Looking for keyfile in SD Card ..." >&2
    mount /dev/mmcblk0p1 $MD -t $PARTTYPE -o ro 2>/dev/null

    if [ -f $MD/$KEYF ]; then
        cat $MD/$KEYF
        umount $MD 2>/dev/null
        OPENED=1
    else
        echo "> Could not find keyfile in SD Card ..." >&2
    fi
    umount $MD 2>/dev/null

# Try getting file from USB Device
    if [ $OPENED -eq 0 ]; then
        echo "> Now looking for keyfile in USB disk(s)..." >&2
# Sleep to allow USB drive to be recognised
        sleep 7
        for SFS in /sys/block/sd*; do
            DEV=`busybox basename $SFS`
            F=$SFS/${DEV}1/dev
            if [ 0`cat $SFS/removable` -eq 1 -a -f $F ]; then
                echo "> Trying device: $DEV ..." >&2
                mount /dev/${DEV}1 $MD -t $PARTTYPE -o ro 2>/dev/null
                if [ -f $MD/$KEYF ]; then
                    cat $MD/$KEYF
                    umount $MD 2>/dev/null
                    OPENED=1
                    break
                fi
                umount $MD 2>/dev/null
            fi
        done
    fi
fi

# Could not read from physical token.  So ask manual input for passphrase.
# read -s -r PASSPHRASE </dev/console does not display input.
if [ $OPENED -eq 0 ]; then
    echo "> FAILED to find keyfile from a physical keychain ..." >&2
    echo -n "Try to enter your passphrase: " >&2
    read -s -r PASSPHRASE </dev/console
    echo -n "$PASSPHRASE"
    echo -e "\n> Attempting to use provided passphrase ..." >&2
else
    echo "Success loading keyfile from the keychain!" >&2
fi