#!/bin/sh
# Install Elf — the desktop app and the elfd server it runs — from a release.
#
#   curl -fsSL https://elfd.io/install.sh | sh
#   curl -fsSL https://elfd.io/install.sh | sh -s -- --channel nightly
#
# POSIX sh on purpose (dash on Linux, bash 3.2 as /bin/sh on macOS), and it never reads stdin:
# under `curl | sh`, stdin *is this script*, so a `read` would eat the installer.
#
# The payload is checked before anything is unpacked: sha256 always, and the Ed25519 signature when
# the local openssl can do it (stock macOS ships LibreSSL, which cannot — hence --require-signature
# for anyone who wants that to be fatal). Verified against the release that published it, not
# against a copy that could drift.
set -eu

CHANNEL=beta
PREFIX=
SYSTEM=0
SERVER_ONLY=0
UNINSTALL=0
DRY_RUN=0
REQUIRE_SIGNATURE=0
BASE=${ELF_INSTALL_BASE:-https://elfd.io}

usage() {
    cat <<'EOF'
Install Elf (app + elfd) on macOS or Linux.

  --channel beta|nightly   release feed to install from (default: beta)
  --prefix DIR             where to install on Linux (default: ~/.local)
                           on macOS: the folder that gets an Applications dir
  --system                 /usr/local, with sudo when needed
  --server-only            install elfd only (headless host)
  --uninstall              remove what this script installed
  --dry-run                print every step, change nothing
  --require-signature      fail if the Ed25519 signature cannot be verified here
  -h, --help               this text

Environment: ELF_INSTALL_BASE overrides https://elfd.io (tests, mirrors).
EOF
}

say() { printf '%s\n' "$*"; }
step() { printf '→ %s\n' "$*"; }
die() {
    printf 'install.sh: %s\n' "$*" >&2
    exit 1
}

need_value() {
    [ $# -ge 2 ] && [ -n "$2" ] || die "$1 needs a value"
}

# Accept both `--flag value` and `--flag=value`.
while [ $# -gt 0 ]; do
    case $1 in
        --channel) need_value "$@"; CHANNEL=$2; shift 2 ;;
        --channel=*) CHANNEL=${1#*=}; shift ;;
        --prefix) need_value "$@"; PREFIX=$2; shift 2 ;;
        --prefix=*) PREFIX=${1#*=}; shift ;;
        --system) SYSTEM=1; shift ;;
        --server-only) SERVER_ONLY=1; shift ;;
        --uninstall) UNINSTALL=1; shift ;;
        --dry-run) DRY_RUN=1; shift ;;
        --require-signature) REQUIRE_SIGNATURE=1; shift ;;
        -h | --help) usage; exit 0 ;;
        *) usage >&2; die "unknown argument: $1" ;;
    esac
done

case $CHANNEL in
    beta | nightly) ;;
    *) die "--channel must be beta or nightly (got $CHANNEL)" ;;
esac

# --------------------------------------------------------------------------- platform
os=$(uname -s)
arch=$(uname -m)
case $os in
    Darwin)
        case $arch in
            arm64) PLATFORM=darwin-aarch64 ;;
            x86_64) PLATFORM=darwin-x86_64 ;;
            *) die "no build for macOS/$arch" ;;
        esac
        ;;
    Linux)
        case $arch in
            x86_64 | amd64) PLATFORM=linux-x86_64 ;;
            aarch64 | arm64) PLATFORM=linux-aarch64 ;;
            *) die "no build for Linux/$arch" ;;
        esac
        ;;
    *) die "unsupported system: $os (macOS and Linux only)" ;;
esac

# The app's own name and the binary names inside the archive, per channel.
if [ "$CHANNEL" = nightly ]; then
    APP_NAME="Elf Nightly.app"
    APP_BIN=elf-nightly
else
    APP_NAME="Elf.app"
    APP_BIN=elf
fi

if [ "$SYSTEM" -eq 1 ]; then
    PREFIX=${PREFIX:-/usr/local}
else
    PREFIX=${PREFIX:-$HOME/.local}
fi
[ -n "$PREFIX" ] || die "empty --prefix"

# macOS installs a bundle, so "prefix" means the folder that contains Applications.
if [ "$os" = Darwin ]; then
    APPS_DIR=$PREFIX/Applications
else
    APPS_DIR=
fi

# --------------------------------------------------------------------------- helpers
need() { command -v "$1" >/dev/null 2>&1 || die "missing required tool: $1"; }

# Make a directory writable by us, or decide we need sudo for it.
#
# A *missing* directory is not a read-only one: testing -w before creating it sent every fresh
# prefix down the sudo path (and `sudo` is not even installed in a slim container).
ensure_dir() { # dir
    if [ "$DRY_RUN" -eq 1 ]; then
        step "would create $1"
        return 0
    fi
    mkdir -p "$1" 2>/dev/null || true
    if [ -d "$1" ] && [ -w "$1" ]; then
        return 0
    fi
    command -v sudo >/dev/null 2>&1 || die "cannot write to $1, and sudo is not installed"
    SUDO=sudo
}

fetch() { # url dest
    curl -fsSL --retry 3 --connect-timeout 15 -o "$2" "$1" || die "cannot download $1"
}

sha256_of() {
    if command -v shasum >/dev/null 2>&1; then
        shasum -a 256 "$1" | awk '{ print $1 }'
    elif command -v sha256sum >/dev/null 2>&1; then
        sha256sum "$1" | awk '{ print $1 }'
    else
        die "no shasum or sha256sum"
    fi
}

# Stock macOS ships LibreSSL, which cannot even load an Ed25519 key; Homebrew's openssl can. Rather
# than guess from version strings, verify a known-good vector once.
PUBKEY_PEM='-----BEGIN PUBLIC KEY-----
MCowBQYDK2VwAyEAZBE2ftMNAUwvmKRKdYBvHr/UtjENNk3Aoal6hCvB7h0=
-----END PUBLIC KEY-----'

PROBE_MSG='elf-installer-probe'
PROBE_SIG='3iQWMtH6qXCCPk7QWARKQ32CDBht0hO9S+toz4snLDIWhr6DJeePy58Hm4mVPVBCQ71ixzCXTVjKPbAqo07PAg=='

# Verify a *known* signature over a *known* message with the shipped public key.
#
# Two jobs at once: it tells us whether this openssl can do Ed25519 at all (stock macOS ships
# LibreSSL 3.3, which cannot even load such a key), and it proves the embedded key is the one the
# releases are signed with — a script with the wrong key would fail here instead of silently
# "verifying" artefacts nobody published.
ed25519_available() {
    command -v openssl >/dev/null 2>&1 || return 1
    probe=$(mktemp -d 2>/dev/null) || return 1
    printf '%s\n' "$PUBKEY_PEM" >"$probe/pub.pem"
    printf '%s' "$PROBE_MSG" >"$probe/msg"
    if ! printf '%s' "$PROBE_SIG" | openssl base64 -d -A -out "$probe/sig" 2>/dev/null; then
        rm -rf "$probe"
        return 1
    fi
    openssl pkeyutl -verify -pubin -inkey "$probe/pub.pem" -rawin \
        -in "$probe/msg" -sigfile "$probe/sig" >/dev/null 2>&1
    status=$?
    rm -rf "$probe"
    return $status
}

verify_payload() { # file base64-signature
    file=$1
    sig_b64=$2
    actual=$(sha256_of "$file")
    [ "$actual" = "$SHA256" ] || die "sha256 mismatch: release says $SHA256, got $actual"
    step "sha256 ok ($actual)"

    if ed25519_available; then
        sig_dir=$(mktemp -d)
        printf '%s\n' "$PUBKEY_PEM" >"$sig_dir/pub.pem"
        printf '%s' "$sig_b64" | openssl base64 -d -A -out "$sig_dir/sig" || die "bad signature encoding"
        if openssl pkeyutl -verify -pubin -inkey "$sig_dir/pub.pem" -rawin \
            -in "$file" -sigfile "$sig_dir/sig" >/dev/null 2>&1; then
            step "signature ok (Ed25519)"
        else
            rm -rf "$sig_dir"
            die "signature does not match the release key"
        fi
        rm -rf "$sig_dir"
    elif [ "$REQUIRE_SIGNATURE" -eq 1 ]; then
        die "cannot verify the Ed25519 signature here (openssl too old); drop --require-signature to proceed on sha256 + TLS alone"
    else
        say "note: this openssl cannot check Ed25519 signatures; sha256 + TLS only."
        say "      re-run with --require-signature to make that fatal instead."
    fi
}

# --------------------------------------------------------------------------- metadata
step "channel $CHANNEL, platform $PLATFORM"
meta_file=$(mktemp)
trap 'rm -f "$meta_file"' EXIT HUP INT TERM
# Even in a dry run this one is fetched: it is a few hundred bytes, read-only, and the whole point
# of a dry run is to show what the *real* run would do.
fetch "$BASE/v1/$CHANNEL/install/$PLATFORM" "$meta_file"
grep -q '^version=' "$meta_file" || die "no build published for $PLATFORM on $CHANNEL"

field() { sed -n "s/^$1=//p" "$meta_file" | head -1; }
VERSION=$(field version)
URL=$(field url)
SHA256=$(field sha256)
SIG=$(field sig)
SIZE=$(field size)
[ -n "$URL" ] || die "install metadata has no url"

say "Elf $VERSION ($CHANNEL) for $PLATFORM"
say "installing into $PREFIX"

# --------------------------------------------------------------------------- uninstall
if [ "$UNINSTALL" -eq 1 ]; then
    # Both channels, whatever --channel says: whoever asks to uninstall wants everything this script
    # put there, and "you forgot --channel nightly" is not a message anyone should have to read.
    if [ "$os" = Darwin ]; then
        targets="$APPS_DIR/Elf.app $APPS_DIR/Elf Nightly.app"
    else
        targets="$PREFIX/bin/elf $PREFIX/bin/elf-nightly $PREFIX/bin/elfd \
            $PREFIX/share/applications/elf.desktop $PREFIX/share/applications/elf-nightly.desktop"
    fi
    if [ "$os" = Darwin ]; then
        [ -w "$APPS_DIR" ] || SUDO=sudo
    else
        [ -w "$PREFIX" ] || SUDO=sudo
    fi
    for target in $targets; do
        if [ -e "$target" ]; then
            step "removing $target"
            [ "$DRY_RUN" -eq 1 ] || ${SUDO:-} rm -rf "$target"
        fi
    done
    if [ "$os" = Linux ]; then
        for icon in "$PREFIX/share/icons/hicolor/256x256/apps/elf.png" \
            "$PREFIX/share/icons/hicolor/256x256/apps/elf-nightly.png"; do
            [ ! -e "$icon" ] || { step "removing $icon"; [ "$DRY_RUN" -eq 1 ] || ${SUDO:-} rm -f "$icon"; }
        done
        # Prune the directories this install created, but only while they are empty: `rmdir` on a
        # share/ tree that holds someone else's files fails harmlessly, and $PREFIX is never touched.
        for dir in \
            "$PREFIX/share/icons/hicolor/256x256/apps" \
            "$PREFIX/share/icons/hicolor/256x256" \
            "$PREFIX/share/icons/hicolor" \
            "$PREFIX/share/icons" \
            "$PREFIX/share/applications" \
            "$PREFIX/share" \
            "$PREFIX/bin"; do
            [ "$DRY_RUN" -eq 1 ] || ${SUDO:-} rmdir "$dir" 2>/dev/null || true
        done
    elif [ -n "$APPS_DIR" ]; then
        [ "$DRY_RUN" -eq 1 ] || ${SUDO:-} rmdir "$APPS_DIR" 2>/dev/null || true
    fi
    say "done. (config and data directories are left alone: ~/.config/elf* and the server's data dir)"
    exit 0
fi

# --------------------------------------------------------------------------- download
work=$(mktemp -d)
trap 'rm -rf "$work" "$meta_file"' EXIT HUP INT TERM
archive=$work/$(basename "$URL")
if [ "$DRY_RUN" -eq 1 ]; then
    step "would download $(basename "$URL") ($SIZE bytes) and verify sha256 + signature"
else
    step "downloading $(basename "$URL")"
    fetch "$URL" "$archive"
    verify_payload "$archive" "$SIG"
fi

# --------------------------------------------------------------------------- install
if [ "$os" = Darwin ]; then
    [ "$DRY_RUN" -eq 1 ] || need ditto
    # A prefix we just made is ours; /Applications is writable for admins; anything else needs sudo.
    ensure_dir "$APPS_DIR"
    # Unpack beside the target and check the bundle is really there *before* removing anything: a
    # payload that does not unpack must not cost the user the copy they already had.
    unpack=$work/unpack
    step "unpacking $APP_NAME"
    [ "$DRY_RUN" -eq 1 ] || mkdir -p "$unpack"
    [ "$DRY_RUN" -eq 1 ] || ditto -x -k "$archive" "$unpack"
    [ "$DRY_RUN" -eq 1 ] || [ -d "$unpack/$APP_NAME" ] || die "the archive did not contain $APP_NAME"
    step "removing any previous $APP_NAME"
    [ "$DRY_RUN" -eq 1 ] || ${SUDO:-} rm -rf "$APPS_DIR/$APP_NAME"
    if [ "$SERVER_ONLY" -eq 1 ]; then
        # Headless macOS host: take the server out of the bundle and leave the app behind.
        ensure_dir "$PREFIX/bin"
        [ "$DRY_RUN" -eq 1 ] || [ -x "$unpack/$APP_NAME/Contents/MacOS/elfd" ] ||
            die "the archive does not contain $APP_NAME/Contents/MacOS/elfd"
        [ "$DRY_RUN" -eq 1 ] || ${SUDO:-} install -m 755 \
            "$unpack/$APP_NAME/Contents/MacOS/elfd" "$PREFIX/bin/elfd"
        say "installed $PREFIX/bin/elfd"
        exit 0
    fi
    step "installing $APP_NAME into $APPS_DIR"
    [ "$DRY_RUN" -eq 1 ] || ${SUDO:-} ditto "$unpack/$APP_NAME" "$APPS_DIR/$APP_NAME"
    # curl sets no quarantine flag, so the app launches without a Gatekeeper detour. That changes
    # once releases are notarized (plan P6), where `spctl` becomes the gate instead.
    say ""
    if [ "$DRY_RUN" -eq 1 ]; then
        say "would install $APPS_DIR/$APP_NAME"
    else
        say "installed $APPS_DIR/$APP_NAME"
        say "open it with:  open \"$APPS_DIR/$APP_NAME\""
    fi
    exit 0
fi

# Linux: a tarball with the app, elfd, launcher and icons.
unpack=$work/unpack
step "unpacking"
[ "$DRY_RUN" -eq 1 ] || mkdir -p "$unpack"
[ "$DRY_RUN" -eq 1 ] || tar -xzf "$archive" -C "$unpack" || die "cannot unpack the archive"
# The archive is named after the directory it contains (`elf-nightly-0.0.4-linux-x86_64`), so no
# `find` is needed — which matters, because a slim Linux image may not have findutils.
root=$unpack/$(basename "$archive" .tar.gz)
[ "$DRY_RUN" -eq 1 ] || [ -d "$root" ] || die "archive does not contain $(basename "$root")"

ensure_dir "$PREFIX"
ensure_dir "$PREFIX/bin"
step "installing binaries into $PREFIX/bin"
[ "$DRY_RUN" -eq 1 ] || ${SUDO:-} install -m 755 "$root/$APP_BIN" "$PREFIX/bin/$APP_BIN"
# The app spawns `elfd` as a sibling of its own executable, so the two must travel together.
[ "$DRY_RUN" -eq 1 ] || ${SUDO:-} install -m 755 "$root/elfd" "$PREFIX/bin/elfd"
say "installed $PREFIX/bin/$APP_BIN and $PREFIX/bin/elfd"

if [ "$SERVER_ONLY" -eq 0 ]; then
    step "installing the launcher and icon"
    ensure_dir "$PREFIX/share/applications"
    ensure_dir "$PREFIX/share/icons/hicolor/256x256/apps"
    if [ "$DRY_RUN" -eq 1 ]; then
        step "would write $PREFIX/share/applications/$APP_BIN.desktop"
    else
        # Same content the release ships, with the paths this prefix needs.
        ${SUDO:-} sed "s|^Exec=.*|Exec=$PREFIX/bin/$APP_BIN|" "$root/desktop/$APP_BIN.desktop" \
            >"$work/$APP_BIN.desktop" 2>/dev/null ||
            ${SUDO:-} cp "$root/$APP_BIN.desktop" "$work/$APP_BIN.desktop"
        ${SUDO:-} install -m 644 "$work/$APP_BIN.desktop" "$PREFIX/share/applications/$APP_BIN.desktop"
        ${SUDO:-} install -m 644 "$root/icons/hicolor/256x256/apps/$APP_BIN.png" \
            "$PREFIX/share/icons/hicolor/256x256/apps/$APP_BIN.png"
    fi
fi

say ""
if [ "$DRY_RUN" -eq 1 ]; then
    # A dry run that ends with "installed" is a dry run nobody trusts twice.
    say "would install Elf $VERSION ($CHANNEL) into $PREFIX"
    exit 0
fi
say "installed Elf $VERSION ($CHANNEL)"
case :$PATH: in
    *:"$PREFIX/bin":*) ;;
    *) say "add it to your PATH:  export PATH=\"$PREFIX/bin:\$PATH\"" ;;
esac
[ "$SERVER_ONLY" -eq 1 ] && say "run it with:  elfd --port 8787 --data-dir ~/.elf-data"
[ "$SERVER_ONLY" -eq 0 ] && say "run it with:  $APP_BIN"
