#!/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/

update_symlink() {
  local dir="$1"
  local target="$2"
  local link="$3"
  if [ -e "$dir/$target" ]; then
    # update the symlink
    $E ln -sf "$target" "$dir/$link"
  else
    # delete the symlink
    $E rm -f "$dir/$link"
  fi
}

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"
        update_symlink "$i/bin" "$NEWVERSION"         "barnowl.real$B"
        update_symlink "$i/bin" "$NEWVERSION.zephyr3" "barnowl.real$B.zephyr3"
        update_symlink "$i/bin" "$NEWVERSION.zephyr4" "barnowl.real$B.zephyr4"

        $E ln -sf "../../common/bin/zcrypt" "$i/bin/zcrypt"
        update_symlink "$i/bin" "zcrypt${NEWVERSION#barnowl}"         "zcrypt.real"
        update_symlink "$i/bin" "zcrypt${NEWVERSION#barnowl}.zephyr3" "zcrypt.real.zephyr3"
        update_symlink "$i/bin" "zcrypt${NEWVERSION#barnowl}.zephyr4" "zcrypt.real.zephyr4"
    fi
done;
