#!/bin/sh

## hyphop ##

#= simple krescue mega image write example

USAGE(){ echo "megaimage - simple krescue mega image write examples
USAGE

output to KRESCUE.sd.mega.img

    ./megaimage.sh KRESCUE.sd.img.gz IMAGE.kresq [ IMAGE.kresq ] ...

output to stdout

    ./megaimage.sh VIM3L.krescue.sd.img.gz *.kresq > VIM3L.krescue.sd.mega.img

write to sd card

    ./megaimage.sh VIM3L.krescue.sd.img.gz *.kresq | dd bs=1M of=/dev/sdX

ABOUT

    + https://dl.khadas.com/Firmware/Krescue/mega/README.megaimage.txt
    + https://dl.khadas.com/Firmware/Krescue/mega/
    + https://dl.khadas.com/Firmware/Krescue/system/

" >&2

exit 1
}

[ "$1" ] || USAGE

for a in $@; do
    case "$a" in
    -A|--autoinstall)
    AUTOINSTALL=1
    shift
    ;;
    *.img.gz)
    Q="$a"
    shift
    ;;
    *.kresq|*.zst|*.zstd)
    ;;
    esac
done

gzip -l "$Q" 2>/dev/null 1>&2 || USAGE

for i in $@; do
    tail -c16 $i | grep -q "##KRESCUE##END" || USAGE
done

T="$(readlink /proc/$$/fd/1)"
O="$(basename "$Q")"
O="${O%.img.gz}.mega.img"

MEGA(){
echo "[i] OUT to $O">&2
gzip -dc "$Q"
cat "$@"

    [ "$AUTOINSTALL" ] && {
    echo "[i] autoinstall configure">&2
    [ "$NOOP" ] || \
    echo "
##KRESCUE_CONFIG##
autoinstall: 1
##KRESCUE-CONFIG##
"
    }

}

case $T in
    /dev/pts*)
    ;;
    /dev/tty*)
    ;;
    *pipe:*)
    O="PIPE"
    MEGA "$@"
    sync
    exit 0
    ;;
    *)
    O="$T"
esac

MEGA "$@" > $O
sync
