#!/bin/bash
# get.autodarts.io — the address the Autodarts 0.x (v1) headless installer has always had,
# handing over to v2.
#
#   bash <(curl -sL get.autodarts.io)                  installs the v2 headless board
#   bash <(curl -sL get.autodarts.io) --uninstall      removes v1 and v2 (--purge: and settings)
#   bash <(curl -sL get.autodarts.io) 0.20.0           a v1 version: the v1 installer, as before
#
# v2 is installed by https://autodarts.sh, which also removes a v1 install it finds. This
# script only translates the old command into that one; the v1 installer it replaces is kept
# as install_autodarts_headless_v1.sh and is still what runs in two cases:
#
#   - Without a terminal. v1's own updater (updater.sh, started at boot by
#     autodartsupdater.service, often as root) calls this address whenever a newer v1 is
#     listed. v2 is not installed onto a machine nobody is watching, so it keeps getting v1.
#   - A pinned 0.x version, which only the v1 installer can install.
set -euo pipefail

V1_URL="https://get.autodarts.io/sh/install_autodarts_headless_v1.sh"
V2_URL="https://autodarts.sh"

run_v1() {
    exec bash <(curl -fsSL "$V1_URL") "$@"
}

if [ ! -t 0 ] || [ ! -t 1 ]; then
    run_v1 "$@"
fi
for arg in "$@"; do
    case "$arg" in
        0.*|v0.*) run_v1 "$@" ;;
    esac
done

v2_script="$(mktemp)"
trap 'rm -f "$v2_script"' EXIT
curl -fsSL "$V2_URL" -o "$v2_script"

case "${1:-}" in
    --uninstall|--purge)
        # v1's uninstall first: it also deletes ~/.local/bin/autodarts, which is v2's command,
        # so v2's own uninstall has to come after it rather than before.
        if [ -f /etc/systemd/system/autodarts.service ] || [ -d "${HOME}/.local/opt/autodarts" ]; then
            bash <(curl -fsSL "$V1_URL") "$1"
        fi
        bash "$v2_script" "$1" --headless
        exit 0
        ;;
esac

# v1's flags that mean nothing to v2: -n (no autostart service; v2 installs one only when
# asked, from its screen) and -u (no auto-updater). Everything else — a track such as `beta`
# — passes through.
args=()
for arg in "$@"; do
    case "$arg" in
        -n|-u|-nu|-un) ;;
        *) args+=("$arg") ;;
    esac
done

echo "get.autodarts.io installs Autodarts v2 now. Next time you can run:"
echo "  curl -fsSL https://autodarts.sh | bash -s -- --headless"
echo
bash "$v2_script" --headless ${args[@]+"${args[@]}"}
