#!/bin/sh

PREREQ=""

prereqs()
{
    echo "$PREREQ"
}

case "$1" in
    prereqs)
        prereqs
        exit 0
        ;;
esac

if [ ! -e /usr/bin/unl0kr ]; then
    exit 0
fi

. /scripts/functions

root_uuid="$(tr ' ' '\n' <  /proc/cmdline | sed -n 's/^unl0kr-root-uuid=//p')"

if [ -z $root_uuid ]; then
    # get encrypted root from cmdline
    # this parameter is required, so quit if it's not there
    if ! grep -qE '^(.*\s)?unl0kr-root=' /proc/cmdline; then
        exit 0
    fi
fi

root_dev=$(blkid --uuid $root_uuid)

if [ -z $root_dev ]; then
    root_dev="$(tr ' ' '\n' <  /proc/cmdline | sed -n 's/^unl0kr-root=//p')"
fi

if [ ! -b "$root_dev" ]; then
    panic "Value for unl0kr-root ($root_dev) is not a valid block device!"
fi

root_name="$(tr ' ' '\n' <  /proc/cmdline | sed -n 's/^unl0kr-root-name=//p')"
[ -z "$root_name" ] && root_name="root"

# TODO: some of these are specific to certain hardware...
export ETNA_MESA_DEBUG=no_supertile
export SDL_VIDEODRIVER=kmsdrm

plymouth hide-splash 2>/dev/null
ttymode=$(stty -g)
stty -echo -icanon min 0 time 0

log_begin_msg "unl0kr starting."

export CRYPTTAB_SOURCE="$root_dev"
export CRYPTTAB_TRIED="0"
export PATH="/usr/sbin:$PATH"

file="temp"

while [ ! -e "$file" ]
do
    res=$(/usr/bin/unl0kr)

    (echo $res) | (/usr/sbin/cryptsetup luksOpen --test-passphrase "$root_dev" && (touch $file))

    if [ -e "$file" ]; then
        (echo $res) | (/usr/sbin/cryptsetup open "$root_dev" "$root_name" -)
    else
        echo "Incorrect password. Try again..."
    fi
done

rm $file

stty "$ttymode"

log_end_msg "unl0kr done."
plymouth show-splash 2>/dev/null

exit 0
