#!/bin/sh
# Downloads an Ultron build from Crouton into the current directory.
# Usage: curl -fsSL <crouton url> | sh
#        curl -fsSL <crouton url> | sh -s -- <branch>
# Crouton replaces https://dl.ashrayshah.dev when it serves this file.
set -eu

base="https://dl.ashrayshah.dev"
out="ultron.sh"

if ! { : </dev/tty; } 2>/dev/null; then
    echo "No terminal available for the prompts." >&2
    exit 1
fi

work=$(mktemp -d)
cleanup() {
    stty echo </dev/tty 2>/dev/null || true
    rm -rf "$work"
}
trap cleanup EXIT
trap 'exit 130' INT TERM

printf 'Password: ' >&2
stty -echo </dev/tty
IFS= read -r password </dev/tty
stty echo </dev/tty
echo >&2

# The header goes to curl on stdin so the password never shows in ps.
auth=$(printf ':%s' "$password" | base64 | tr -d '\n')
unset password

fetch() {
    code=$(printf 'Authorization: Basic %s\n' "$auth" | curl -sS -H @- -o "$2" -w '%{http_code}' "$1") || return 1
    case "$code" in
        200) ;;
        401) echo "Wrong password." >&2; return 1 ;;
        404) echo "Not found: $1" >&2; return 1 ;;
        *) echo "Server answered $code for $1" >&2; return 1 ;;
    esac
}

fetch "$base/branches" "$work/branches"
if [ ! -s "$work/branches" ]; then
    echo "The server has no branches yet." >&2
    exit 1
fi

branch="${1:-}"
if [ -z "$branch" ]; then
    echo "Branches, newest first:" >&2
    awk '{ printf "  %d) %s\n", NR, $0 }' "$work/branches" >&2
    printf 'Pick a number or a name [1]: ' >&2
    IFS= read -r choice </dev/tty
    choice="${choice:-1}"
    case "$choice" in
        *[!0-9]*) branch="$choice" ;;
        *) branch=$(sed -n "${choice}p" "$work/branches") ;;
    esac
fi

if [ -z "$branch" ] || ! grep -Fxq -- "$branch" "$work/branches"; then
    echo "No such branch." >&2
    exit 1
fi

fetch "$base/branch/$branch" "$work/$out"
if [ ! -s "$work/$out" ]; then
    echo "Downloaded file is empty." >&2
    exit 1
fi
chmod +x "$work/$out"
mv -f "$work/$out" "./$out"
echo "Saved ./$out from branch $branch." >&2
