#!/bin/sh

PREREQ=""

prereqs()
{
       echo "$PREREQ"
}

case $1 in
# get pre-requisites
    prereqs)
           prereqs
           exit 0
           ;;
esac

. /scripts/casper-functions

extract_file()
{
    FILE="$1"
    if [ -z "$FILE" ]; then
        return
    fi
    case "${FILE##*.}" in
        (iso|ISO)
            echo "LIVEMEDIA=$FILE" >> /conf/param.conf
            echo "LIVEMEDIA_OFFSET=0" >> /conf/param.conf
            ;;
            # Maybe cooperate with debian-installer/driver-update=* of casper and debian-installer/custom-installation=* of lupin-casper.
        (tar|TAR)
            tar xf "$FILE" -C /isodevice && rm "$FILE"
            ;;
        (deb)
            if [ ! -d /isodevice/debs ]; then
                mkdir -p /isodevice/debs
            fi
            mv -v $FILE /isodevice/debs/
            ;;
        (lst|list)
            cat $FILE | while read item; do
                NEXT="/isodevice/$(basename ${item})"
                if wget "$item" -O "${NEXT}"; then
                    extract_file "$NEXT"
                else
                    panic "
Could not fetch $item
This could also happen if the network is unstable or the target doesn't exist. 
"
                fi
            done
            rm "$FILE"
            ;;
        (*)
            ;;
    esac
}

fetch_file()
{
    FETCH="$1"
    FILE="/isodevice/$(basename ${FETCH})"
    if [ -n "${FETCH}" ]; then
        if [ ! -d /isodevice ]; then
            modprobe "${MP_QUIET}" af_packet # For DHCP
            configure_networking

            mkdir -p /isodevice
            mount -t ramfs ram /isodevice
        fi

        if wget "${FETCH}" -O "${FILE}"; then
            extract_file ${FILE}
        else
            umount /isodevice
            rmdir /isodevice
            panic "
Could not fetch $FETCH
This could also happen if the network is unstable or the target doesn't exist. 
"
        fi
    fi
}

for x in $(cat /proc/cmdline); do
    case ${x} in
        (fetch=*)
            fetch_file ${x#fetch=}
            ;;
    esac
done

