#!/bin/sh

case ",$DEBUG_SH," in
*,pkg,*|*,${1:-no},*) set -x;;
esac

case "${PKGSET:-active}" in
active|pending|validate) ;;
*) exit 0;;
esac

old_4th=
new_4th=:
MACHINE=${MACHINE:-`uname -m`}
efi_version=${EFI_VERSION:-`kenv -q efi-version`}
board_name=${BOARD_NAME:=`kenv -q hw.board.name`}

case "${efi_version:-0},$MACHINE,$board_name" in
*,mips*|*,oceteon*) old_4th=: new_4th=;; # new 4th
0,*|*,acx-710) ;;		# old 4th
*) old_4th=: new_4th=;;		# new 4th
esac
hash=sha1

case "$VOLUME" in
snapshot) not_snapshot=: snapshot=;;
*) not_snapshot= snapshot=: ;;
esac

# we like to avoid updating /boot
for t in ${PKGDIR}/contents/*-boot.tar
do
    test -s $t || continue
    C=
    sub=
    b=`basename $t -boot.tar`
    case "$b" in
    loader-ve)
        the_sig=$DESTDIR/boot/loader-manifest.esig;;
    loader) # only update if not veloader
        test -s $DESTDIR/boot/veloader && continue
        the_sig=$DESTDIR/boot/loader-manifest.esig
        ;;
    junos*)
        $snapshot continue
        $new_4th continue
        the_sig=$DESTDIR/boot/manifest.esig
        ;;
    volume-junos)
        $snapshot continue
        $old_4th continue
        the_sig=$DESTDIR/boot/manifest.esig
        ;;
    snapshot*)
        $not_snapshot continue
        $new_4th continue
        the_sig=$DESTDIR/boot/manifest.esig
        ;;
    volume-snapshot*)
        $not_snapshot continue
        $old_4th continue
        the_sig=$DESTDIR/boot/manifest.esig
        ;;
    *)  $old_4th continue
        sub=/$b
        C=boot
        the_sig=$DESTDIR/boot$sub/manifest.esig
        ;;
    esac
    if test -s $the_sig; then
        want=`cat ${t%.tar}.hash`
        have=`$hash < $the_sig`
        test x$have = x$want && continue
    fi
    echo Updating $DESTDIR/boot$sub ${t##*/} ...
    tar xf $t -C $DESTDIR/$C
done
