#!/bin/sh
set -eu

API="https://git.fristy.net/api/v1/repos/fristy/frislit/releases/latest"
BASE="https://git.fristy.net/fristy/frislit/releases/download"

say() { printf '  %s\n' "$*"; }
fail() { printf 'frislit: %s\n' "$*" >&2; exit 1; }
have() { command -v "$1" >/dev/null 2>&1; }

os=$(uname -s)
arch=$(uname -m)

case "$arch" in
    x86_64|amd64) arch=x64 ;;
    aarch64|arm64) arch=arm64 ;;
    *) fail "unsupported architecture: $arch. frislit ships for x86-64 and ARM64." ;;
esac

[ "$os" = "Linux" ] || fail "unsupported operating system: $os. Build from source: https://git.fristy.net/fristy/frislit"

fetch() {
    if have curl; then curl -fsSL "$1" -o "$2"
    elif have wget; then wget -qO "$2" "$1"
    else fail "curl or wget is required"
    fi
}

if [ "$(id -u)" -eq 0 ]; then SUDO=""; elif have sudo; then SUDO="sudo"; else SUDO=""; fi

printf '\n  frislit installer (%s %s)\n\n' "$os" "$arch"

tag=$(fetch "$API" /dev/stdout 2>/dev/null | sed -n 's/.*"tag_name":"\([^"]*\)".*/\1/p' | head -1)
[ -n "$tag" ] || fail "could not read the latest release from $API"

asset="frislit-linux-$arch"
say "Downloading $tag/$asset"
tmp=$(mktemp)
fetch "$BASE/$tag/$asset" "$tmp"
chmod +x "$tmp"

if [ -w /usr/local/bin ] || [ -n "$SUDO" ]; then
    $SUDO install -m 755 "$tmp" /usr/local/bin/frislit
    target=/usr/local/bin/frislit
else
    mkdir -p "$HOME/.local/bin"
    install -m 755 "$tmp" "$HOME/.local/bin/frislit"
    target="$HOME/.local/bin/frislit"
    case ":$PATH:" in *":$HOME/.local/bin:"*) ;; *) say "Add $HOME/.local/bin to your PATH" ;; esac
fi
rm -f "$tmp"

printf '\n  Installed %s\n\n' "$target"
if have frislit; then say "$(frislit --version)"; else say "Open a new terminal to use frislit."; fi
say "Next: frislit login"
printf '\n'
