#!/bin/sh
# ascii-scenes installer: https://github.com/mathematicalmichael/scenes
#
#   curl -fsSL https://scenes.math.computer/install.sh | bash
#
# Puts one small program, `ascii-scenes`, into ~/.local/bin. No sudo, nothing else is touched.
# Run it again any time to update; it does nothing if you already have the newest version.
#
#   a specific version:   curl -fsSL https://scenes.math.computer/install.sh | bash -s -- --version 20261204rc0
#   another folder:       curl -fsSL https://scenes.math.computer/install.sh | bash -s -- --dir /usr/local/bin
#   remove it:            rm ~/.local/bin/ascii-scenes
#
# The same as environment variables: SCENES_VERSION, SCENES_INSTALL_DIR.

set -eu

BASE_URL="${SCENES_BASE_URL:-https://scenes.math.computer}"

if [ -t 1 ] && [ -z "${NO_COLOR:-}" ]; then
    B=$(printf '\033[1m') D=$(printf '\033[2m') R=$(printf '\033[31m') G=$(printf '\033[32m') N=$(printf '\033[0m')
else
    B='' D='' R='' G='' N=''
fi

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

usage() {
    cat <<USAGE
Install or update ascii-scenes.

  --version V   install version V (e.g. 20261204-rc0) instead of the newest
  --dir DIR     install into DIR (default: ~/.local/bin)
  -h, --help    show this help
USAGE
}

# fetch URL FILE
fetch() {
    if have curl; then
        curl -fsSL --proto '=https,http' --retry 3 -o "$2" "$1"
    else
        wget -q -O "$2" "$1"
    fi
}

sha256_of() {
    if have sha256sum; then
        sha256sum "$1" | cut -d' ' -f1
    elif have shasum; then
        shasum -a 256 "$1" | cut -d' ' -f1
    elif have openssl; then
        openssl dgst -sha256 "$1" | sed 's/^.*= *//'
    else
        return 1
    fi
}

TMP=''
cleanup() {
    [ -z "$TMP" ] || rm -rf "$TMP"
    TMP=''
}

main() {
    version="${SCENES_VERSION:-}"
    dir="${SCENES_INSTALL_DIR:-}"
    while [ $# -gt 0 ]; do
        case "$1" in
            --version)
                [ $# -ge 2 ] || die "--version needs a value, e.g. --version 20261204-rc0"
                version=$2
                shift 2
                ;;
            --version=*)
                version=${1#*=}
                shift
                ;;
            --dir)
                [ $# -ge 2 ] || die "--dir needs a folder"
                dir=$2
                shift 2
                ;;
            --dir=*)
                dir=${1#*=}
                shift
                ;;
            -h | --help)
                usage
                exit 0
                ;;
            *) die "unknown option: $1 (try --help)" ;;
        esac
    done

    have curl || have wget || die "this needs curl or wget; install one of them and try again"

    # Which build fits this machine.
    case "$(uname -s)" in
        Linux) os=linux ;;
        Darwin) os=macos ;;
        *) die "ascii-scenes runs on Linux and macOS (this is $(uname -s)). On Windows, use WSL." ;;
    esac
    machine=$(uname -m)
    case "$machine" in
        x86_64 | amd64) arch=x86_64 ;;
        aarch64 | arm64) arch=arm64 ;;
        armv7* | armv8l) arch=armv7 ;;
        armv6*) arch=armv6 ;;
        *) die "there is no build for this processor ($machine)" ;;
    esac
    if [ "$os" = macos ]; then
        case "$arch" in
            x86_64)
                # A shell running under Rosetta reports x86_64 on an Apple silicon Mac.
                if [ "$(sysctl -n sysctl.proc_translated 2>/dev/null || true)" = 1 ]; then
                    arch=arm64
                else
                    # No Intel Mac build for now (remove this branch when macos-x86_64 is published again).
                    die "there is no build for Intel Macs yet, only for Apple silicon (M1 and later)"
                fi
                ;;
            arm64) ;;
            *) die "there is no macOS build for this processor ($machine)" ;;
        esac
    fi
    # The armv7 build uses NEON; the few ARMv7 chips without it get the armv6 build.
    if [ "$os" = linux ] && [ "$arch" = armv7 ] && [ -r /proc/cpuinfo ]; then
        grep -qiE '^(features|flags).*[[:space:]](neon|asimd)([[:space:]]|$)' /proc/cpuinfo || arch=armv6
    fi
    asset="ascii-scenes-$os-$arch"

    [ -n "$dir" ] || {
        [ -n "${HOME:-}" ] || die "HOME is not set; pass --dir DIR"
        dir="$HOME/.local/bin"
    }
    mkdir -p "$dir" 2>/dev/null || die "cannot create $dir"
    [ -w "$dir" ] || die "cannot write to $dir (pick another folder with --dir)"
    dir=$(cd "$dir" && pwd)
    dest="$dir/ascii-scenes"

    TMP=$(mktemp -d "$dir/.ascii-scenes-install.XXXXXX") || die "cannot create a temporary folder in $dir"
    trap cleanup EXIT
    trap 'exit 130' INT
    trap 'exit 143' TERM HUP
    trap 'exit 141' PIPE

    if [ -z "$version" ]; then
        fetch "$BASE_URL/latest" "$TMP/latest" || die "could not reach $BASE_URL (are you online?)"
        version=$(tr -d ' \t\r\n' <"$TMP/latest")
        [ -n "$version" ] || die "$BASE_URL/latest is empty"
    fi
    version=${version#scenes-}
    case "$version" in
        *[!0-9A-Za-z._-]* | .* | '') die "that does not look like a version: $version" ;;
    esac
    rel="$BASE_URL/releases/$version"

    fetch "$rel/SHA256SUMS" "$TMP/sums" ||
        die "version $version was not found at $BASE_URL (versions look like 20261204-rc0)"
    want=$(awk -v f="$asset" '$2 == f || $2 == "*" f { print $1; exit }' "$TMP/sums")
    [ -n "$want" ] || die "version $version has no build for $os $arch"

    old=''
    if [ -x "$dest" ]; then
        old=$("$dest" --version 2>/dev/null | awk 'NR == 1 { print $2 }') || old=''
        if [ "$(sha256_of "$dest" 2>/dev/null || true)" = "$want" ] ||
            { ! sha256_of "$dest" >/dev/null 2>&1 && [ "$old" = "$version" ]; }; then
            cleanup
            say "${G}ascii-scenes $version is already installed${N} ${D}($dest)${N}"
            finish
            return 0
        fi
    fi

    say "Downloading ascii-scenes $version for $os $arch ..."
    fetch "$rel/$asset" "$TMP/ascii-scenes" || die "the download failed: $rel/$asset"
    if got=$(sha256_of "$TMP/ascii-scenes"); then
        [ "$got" = "$want" ] ||
            die "the download is damaged (checksum mismatch); nothing was installed. Please try again."
    else
        say "${D}note: no sha256 tool found, so the download was not checked${N}"
    fi
    chmod 755 "$TMP/ascii-scenes"
    "$TMP/ascii-scenes" --version >/dev/null 2>&1 ||
        die "the $os $arch build does not run on this machine; nothing was installed.
       Please report it: https://github.com/mathematicalmichael/scenes/issues"
    mv -f "$TMP/ascii-scenes" "$dest"
    cleanup

    if [ -n "$old" ] && [ "$old" != "$version" ]; then
        say "${G}Updated ascii-scenes $old -> $version${N} ${D}($dest)${N}"
    else
        say "${G}Installed ascii-scenes $version${N} ${D}($dest)${N}"
    fi
    finish
}

# What to do next. Uses dir, dest, os from main.
finish() {
    say ""
    case ":${PATH:-}:" in
        *":$dir:"*)
            other=$(command -v ascii-scenes 2>/dev/null || true)
            if [ -n "$other" ] && [ "$other" != "$dest" ]; then
                say "note: another ascii-scenes comes first on your PATH: $other"
                say "Run this one with:  ${B}$dest${N}"
            else
                say "Run it:  ${B}ascii-scenes${N}"
            fi
            ;;
        *)
            case "${SHELL:-}" in
                */zsh) rc="$HOME/.zshrc" line="export PATH=\"$dir:\$PATH\"" ;;
                */fish) rc="$HOME/.config/fish/config.fish" line="fish_add_path \"$dir\"" ;;
                */bash)
                    rc="$HOME/.bashrc" line="export PATH=\"$dir:\$PATH\""
                    [ "$os" != macos ] || rc="$HOME/.bash_profile"
                    ;;
                *) rc="$HOME/.profile" line="export PATH=\"$dir:\$PATH\"" ;;
            esac
            say "Run it:  ${B}$dest${N}"
            say ""
            say "To be able to type just ${B}ascii-scenes${N}, add its folder to your PATH once,"
            say "then open a new terminal window:"
            say ""
            say "  echo '$line' >> $rc"
            ;;
    esac
    say ""
    say "Keys: ${B}q${N} quit, ${B}h${N} help, ${B}r${N} another landscape, ${B}w${N} live weather on/off. Options: ascii-scenes --help"
    if [ "$os" = macos ]; then
        say "${D}Tip: it looks best in Ghostty or iTerm2; Apple's Terminal shows fewer colors.${N}"
    else
        say "${D}Tip: it looks best in a modern terminal window, as large as you like (GNOME Terminal,${N}"
        say "${D}Konsole, kitty, Ghostty ...). It also runs over SSH and on the bare console, with fewer colors.${N}"
    fi
}

main "$@"
