#!/bin/bash
beta=
dryrun=

usage() {
    echo "Usage: $0 [--dry-run|-n] [--beta|-b] NEW-VERSION" >&2
    exit 1;
}

for arg in "$@"; do
    case $arg in
        --beta|-b)
            beta=1 ;;
        --dry-run|-n)
            dryrun=1 ;;
        -*)
            usage ;;
        *)
            test -n "$NEWVERSION" && usage
            NEWVERSION="$arg"
            ;;
    esac
done

test -z "$NEWVERSION" && usage

# Run this as 'locker-update NEW-VERSION' to upgrade the barnowl.real
# symlink in all arch/ directories to point to the new version.

E=
test -n "$dryrun" && E=echo

B=
test -n "$beta" && B=-beta

cd /mit/barnowl/arch/

for i in *; do
    if [ -L "$i" ]; then
        echo "# Skipping $i as a symbolic link..."
    elif [ "$i" = "common" ]; then
        echo "# Skipping 'common'..."
    elif ! [ -e "$i/bin/$NEWVERSION" ]; then
        echo "# New version $NEWVERSION not built for arch $i...";
    else
        echo "# $i"

        # Sanity -- make sure the 'barnowl' symlink is correct.
        $E ln -sf "../../common/bin/barnowl$B" "$i/bin/barnowl$B"
        [ -e "$i/bin/$NEWVERSION" ]         && $E ln -sf "$NEWVERSION"         "$i/bin/barnowl.real$B"
        [ -e "$i/bin/$NEWVERSION.zephyr3" ] && $E ln -sf "$NEWVERSION.zephyr3" "$i/bin/barnowl.real$B.zephyr3"
        [ -e "$i/bin/$NEWVERSION.zephyr4" ] && $E ln -sf "$NEWVERSION.zephyr4" "$i/bin/barnowl.real$B.zephyr4"

        $E ln -sf "zcrypt${NEWVERSION#barnowl}" "$i/bin/zcrypt"
    fi
done;
