#!/bin/sh -efu
#

mydir=/usr/share/update-nvflash
tmpdir="$(mktemp -dt "update-nvflash.XXXXXXXXXX")"
archive=tegra-linux.tar.gz

source $mydir/files.conf


nvflash_check ()
{
    test -e /usr/bin/nvflash || return 1
    echo "$nvflash_sum  /usr/bin/nvflash" | md5sum --quiet -c - || return 1 

    test -f /usr/lib/nvflash/fastboot.bin || return 1
    echo "$bootloader_sum  /usr/lib/nvflash/fastboot.bin" | md5sum --quiet -c - || return 1

    return 0
}


nvflash_download ()
{
    if [[ $archive_url == file:* ]]; then
        cp ${archive_url#file:} $tmpdir/$archive
    else
        wget $archive_url -O $tmpdir/$archive
    fi
    echo "$archive_sum  $tmpdir/$archive" | md5sum --quiet -c - || exit 1
}


nvflash_run_extract ()
{
    tar xf $tmpdir/$archive -C $tmpdir
    echo "$nvflash_sum  $tmpdir/ldk/bootloader/nvflash" | md5sum --quiet -c - || exit 1
    echo "$bootloader_sum  $tmpdir/ldk/bootloader/harmony/fastboot.bin" | md5sum --quiet -c - || exit 1
}


nvflash_install ()
{
    install -m0755 -D $tmpdir/ldk/bootloader/nvflash /usr/bin/nvflash
    install -m0644 -D $tmpdir/ldk/bootloader/harmony/fastboot.bin /usr/lib/nvflash/fastboot.bin
}


nvflash_clean ()
{
    rm -rf "$tmpdir"
}
trap nvflash_clean EXIT
trap nvflash_clean HUP PIPE INT QUIT TERM


nvflash_remove ()
{
    rm /usr/bin/nvflash || :
    rm /usr/lib/nvflash/fastboot.bin || :
}


nvflash_update ()
{
    nvflash_check && return

    nvflash_download
    nvflash_run_extract
    nvflash_install
    nvflash_clean
}


case "${1:---help}" in
    --install)
        nvflash_update
        ;;
    --remove)
        nvflash_remove
        ;;
    --check)
        if nvflash_check; then
            echo "nvflash: installed - ok"
        else
            echo "nvflash: need to be installed or updated"
        fi
        ;;
    *)
        echo "usage: $0: <--install|--remove|--check>"
        exit 1
        ;;
esac

exit 0

