#!/bin/sh
# Installs {{NAME}} on macOS or Linux.
#
#   curl -fsSL https://raw.githubusercontent.com/{{REPO}}/main/install.sh | bash
#
# (install.ps1 does the same on Windows.)
#
# Downloads the release's {{APP}} for this machine, checks it against the
# release manifest, and runs `{{APP}} install`, which copies it to
# ~/.local/share/{{APP}} (~/Library/Application Support/{{APP}} on macOS).
# The bin folder is added to your PATH in your shell's startup file. After
# that {{NAME}} updates itself.
{{ABOUT}}#
# Set {{ENV}}_VERSION to a release's version (for example 0.1.0) to install
# that release instead of the latest. The app still updates itself to the
# latest release afterwards unless {{ENV}}_DISABLE_AUTOUPDATER is set.
#
# Generated by Abalone's InstallScript: change it there, not here.

set -eu

NAME='{{NAME}}'
APP='{{APP}}'
REPO='{{REPO}}'
VERSION="${{{ENV}}_VERSION:-}"
# A local {{APP}} to install instead of downloading (for testing).
EXE="${{{ENV}}_EXE:-}"

fail() {
    printf 'error: %s\n' "$*" >&2
    exit 1
}

case "$(uname -s)" in
    Linux) os=linux ;;
    Darwin) os=macos ;;
    *) fail "$NAME doesn't run on $(uname -s); on Windows use install.ps1" ;;
esac
case "$(uname -m)" in
    x86_64 | amd64) arch=x64 ;;
    arm64 | aarch64) arch=arm64 ;;
    *) fail "$NAME doesn't run on $(uname -m)" ;;
esac
# A shell running under Rosetta says x86_64 on an Arm Mac.
if [ "$os" = macos ] && [ "$arch" = x64 ] && [ "$(sysctl -n sysctl.proc_translated 2>/dev/null || true)" = 1 ]; then
    arch=arm64
fi
PLATFORM="$os-$arch"

if [ -n "${{{ENV}}_HOME:-}" ]; then
    ROOT="${{ENV}}_HOME"
elif [ "$os" = macos ]; then
    ROOT="$HOME/Library/Application Support/$APP"
else
    ROOT="${XDG_DATA_HOME:-$HOME/.local/share}/$APP"
fi
BIN="$ROOT/bin"

fetch() {
    if command -v curl >/dev/null 2>&1; then
        curl -fsSL "$1" -o "$2" || fail "couldn't download $1"
    elif command -v wget >/dev/null 2>&1; then
        wget -qO "$2" "$1" || fail "couldn't download $1"
    else
        fail "$NAME's installer needs curl or wget"
    fi
}

# Run in $(...), where `fail` would only end the subshell: check `sha256_tool` first.
sha256() {
    if command -v sha256sum >/dev/null 2>&1; then
        sha256sum "$1" | cut -d ' ' -f 1
    else
        shasum -a 256 "$1" | cut -d ' ' -f 1
    fi
}

sha256_tool() {
    command -v sha256sum >/dev/null 2>&1 || command -v shasum >/dev/null 2>&1 ||
        fail "$NAME's installer needs sha256sum or shasum to check the download"
}

# The first string value of a key in JSON squeezed onto one line: `field '"file":'`.
field() {
    grep -o "$1\"[^\"]*\"" | head -n 1 | sed 's/.*:"//; s/"$//'
}

TEMP="$(mktemp -d)"
trap 'rm -rf "$TEMP"' EXIT

echo ''
printf '%s\n' "Installing $NAME"

download="$TEMP/$APP"
if [ -n "$EXE" ]; then
    printf '%s\n' "  Using $EXE"
    cp "$EXE" "$download"
else
    sha256_tool
    if [ -n "$VERSION" ]; then
        # Tags have no v prefix; accept one anyway.
        manifest_url="https://github.com/$REPO/releases/download/${VERSION#v}/manifest.json"
    else
        manifest_url="https://github.com/$REPO/releases/latest/download/manifest.json"
    fi
    fetch "$manifest_url" "$TEMP/manifest.json"
    manifest="$(tr -d ' \t\r\n' <"$TEMP/manifest.json")"
    version="$(printf '%s' "$manifest" | field '"version":')"
    asset="$(printf '%s' "$manifest" | grep -o "\"$PLATFORM\":{[^}]*}" || true)"
    # Arm Macs run x64 builds too (through Rosetta).
    if [ -z "$asset" ] && [ "$PLATFORM" = macos-arm64 ]; then
        asset="$(printf '%s' "$manifest" | grep -o '"macos-x64":{[^}]*}' || true)"
    fi
    [ -n "$asset" ] || fail "release $version has no $PLATFORM build"
    file="$(printf '%s' "$asset" | field '"file":' || true)"
    expected="$(printf '%s' "$asset" | field '"sha256":' | tr 'A-F' 'a-f' || true)"
    [ -n "$file" ] || fail "release $version names no file for $PLATFORM"
    [ -n "$expected" ] || fail "release $version has no SHA-256 for $file"
    printf '%s\n' "  Downloading $NAME $version"
    fetch "https://github.com/$REPO/releases/download/$version/$file" "$download"
    actual="$(sha256 "$download")"
    [ "$actual" = "$expected" ] || fail "$file has SHA-256 $actual, expected $expected"
fi
chmod +x "$download"

# bin on PATH, now and for new terminals.
case ":$PATH:" in
    *":$BIN:"*) ;;
    *)
        case "$(basename "${SHELL:-sh}")" in
            zsh) profile="${ZDOTDIR:-$HOME}/.zshrc" ;;
            bash) if [ "$os" = macos ]; then profile="$HOME/.bash_profile"; else profile="$HOME/.bashrc"; fi ;;
            fish) profile="$HOME/.config/fish/conf.d/$APP.fish" ;;
            *) profile="$HOME/.profile" ;;
        esac
        case "$profile" in
            *.fish) line="fish_add_path \"$BIN\"" ;;
            *) line="export PATH=\"$BIN:\$PATH\"" ;;
        esac
        mkdir -p "$(dirname "$profile")"
        if ! grep -qsF "$line" "$profile"; then
            printf '\n# %s\n%s\n' "$NAME" "$line" >>"$profile"
            printf '%s\n' "  Added $BIN to your PATH in $profile"
        fi
        PATH="$BIN:$PATH"
        ;;
esac

# {{NAME}} copies itself into place.
"$download" install || fail "$APP install failed"
{{AFTER}}
echo ''
printf '%s\n' '{{DONE}}'
echo ''
