#!/bin/sh
#
# $Id: linkjail 7431 2011-04-20 16:57:22Z NiLuJe $
#

# Pull some helper functions for logging
_FUNCTIONS=/etc/rc.d/functions
[ -f ${_FUNCTIONS} ] && . ${_FUNCTIONS}

LINKJAIL_BASEDIR="/mnt/us/linkjail"

# Always assume we do *NOT* want the custom key
want_custom_key="false"

# If there's a trigger file, always assume we want to use the custom key
if [ -f "/mnt/us/ENABLE_HACK_UPDATES" ] ; then
    want_custom_key="true"
fi

# Oh, Windows, how I hate thee... Note the crappy workaround needed for busybox's sed implementation...
sed -e "s/$(echo -ne '\r')$//g" -i ${LINKJAIL_BASEDIR}/etc/whitelist

# Check our whitelist of hacks to see if we need a custom key...
while read wl_hackname ; do
    if [ -n "${wl_hackname}" ] ; then
        for us_binfile in /mnt/us/*pdate*.bin ; do
            case "${us_binfile##*/}" in
                ${wl_hackname}*.bin )
                    # Our update file matches a whitelisted hack, request custom key
                    msg "found an update file matching '${wl_hackname}', requesting custom key" I
                    want_custom_key="true"
                ;;
            esac
        done
    fi
done <${LINKJAIL_BASEDIR}/etc/whitelist

# We want a custom key, enable it...
if [ "${want_custom_key}" == "true" ] ; then
    msg "custom key requested" I

    # Don't mount twice...
    if ! grep "^fsp /etc/uks/pubprodkey01.pem" /proc/mounts > /dev/null 2>&1 ; then
        msg "mounting custom key" I
        mount --bind ${LINKJAIL_BASEDIR}/etc/pubhack.key /etc/uks/pubprodkey01.pem
    else
        msg "looks like the custom key is already mounted" W
    fi
else
    # Default keys. Do an unmount check, just in case...
    msg "default keys requested" I

    if grep "^fsp /etc/uks/pubprodkey01.pem" /proc/mounts > /dev/null 2>&1 ; then
        msg "unmounting custom key" I
        umount -l /etc/uks/pubprodkey01.pem
    else
        msg "nothing to do" I
    fi
fi
