#!/bin/sh
# Installs Forkbase: the `forkbase` binary and, with FORKBASE_ENGINE=1 (or --engine), the Chronos engine (`chronos`)
# that agents' worlds need. It picks the build for this OS and CPU, shows each download as it happens (size, speed,
# time left), retries and resumes a download that stalls, checks every file's SHA-256 against its release's
# SHA256SUMS (and its Sigstore signature when cosign is on PATH), runs the new binary before putting it in place, and
# puts it in ~/.local/bin (or $FORKBASE_INSTALL_DIR). It never runs anything as root: for /usr/local/bin, run it as
# `sudo env FORKBASE_INSTALL_DIR=/usr/local/bin sh install.sh` yourself.
#
#   curl -fsSL https://forkbase.tech/install.sh | FORKBASE_ENGINE=1 sh
#   curl -fsSL https://forkbase.tech/install.sh | sh -s -- --engine
#
# Options (each also an environment variable):
#   --engine / --no-engine   FORKBASE_ENGINE=1|0  also install the Chronos engine (asked when run in a terminal)
#   --version <tag>          FORKBASE_VERSION     a release tag (default: the release this copy came from)
#   --dir <folder>           FORKBASE_INSTALL_DIR where to put the binaries (default ~/.local/bin)
#   --add-path               FORKBASE_ADD_PATH=1  add that folder to your shell's PATH (asked when run in a terminal)
#   --force                  FORKBASE_FORCE=1     reinstall even when the same version is there
#   --setup / --no-setup     FORKBASE_SETUP=1|0   then set up a project: folder, database, start it, open the
#                                                 dashboard (asked when run in a terminal)
#   --project <folder>       FORKBASE_PROJECT     the project's folder (default ./myapp)
#   --db chronos|postgres    FORKBASE_DB          its database: the built-in engine, or your Postgres
#   --database-url <url>     FORKBASE_DATABASE_URL  postgres: the database's URL
#   --no-start               FORKBASE_START=0     set the project up, don't start it
#   --email <address>        FORKBASE_OWNER_EMAIL your dashboard sign-in (asked when run in a terminal); the password
#                            FORKBASE_OWNER_PASSWORD is asked, hidden, or read from this variable
#   --share-email / --no-share-email  FORKBASE_SHARE_EMAIL=1|0  send that email (only) to the Forkbase team so they
#                                                 can follow up (asked when run in a terminal; never sent unasked)
#   --yes                    FORKBASE_YES=1       ask nothing: take the defaults (no setup unless --setup)
#   --quiet                  FORKBASE_QUIET=1     print only errors and the final line
#   --no-color               NO_COLOR=1           plain text
# FORKBASE_VERIFY=1 requires the signature check (and cosign); FORKBASE_VERIFY=0 skips it, with a warning.
# FORKBASE_BASE_URL and FORKBASE_ENGINE_BASE_URL override where the files come from (a mirror, or file:// for tests).
set -eu

# everything runs from main at the end, so a download of this script cut off halfway runs nothing
main() {
REPO="2090-labs/forkbase"
ENGINE_REPO="2090-labs/Chronos-DB"
ENGINE_VERSION="v0.9.3" # the engine this release was tested with
SIGNER_ACCOUNT="chronos-release@project-7a947b34-cb98-4716-8f2.iam.gserviceaccount.com" # the release builds' signer
DOCS="https://forkbase.tech/docs/getting-started"
VERSION="${FORKBASE_VERSION:-v0.9.1}" # filled in at release time; a copy from the repo installs latest
DIR="${FORKBASE_INSTALL_DIR:-$HOME/.local/bin}"
engine="${FORKBASE_ENGINE:-}"
add_path="${FORKBASE_ADD_PATH:-}"
force="${FORKBASE_FORCE:-}"
yes="${FORKBASE_YES:-}"
quiet="${FORKBASE_QUIET:-}"
setup="${FORKBASE_SETUP:-}"
project="${FORKBASE_PROJECT:-}"
db="${FORKBASE_DB:-}"
db_url="${FORKBASE_DATABASE_URL:-}"
start_it="${FORKBASE_START:-}"
owner_email="${FORKBASE_OWNER_EMAIL:-}"
share="${FORKBASE_SHARE_EMAIL:-}"
CONTACT_URL="${FORKBASE_CONTACT_URL:-https://forkbase.tech/api/hello}" # where a shared email goes (only with a yes)

while [ $# -gt 0 ]; do
    case "$1" in
    --engine) engine=1 ;;
    --email) [ $# -ge 2 ] || fail "--email needs an address"; owner_email=$2; shift ;;
    --email=*) owner_email=${1#*=} ;;
    --share-email) share=1 ;;
    --no-share-email) share=0 ;;
    --no-engine) engine=0 ;;
    --version) [ $# -ge 2 ] || fail "--version needs a tag, like v0.2.0"; VERSION=$2; shift ;;
    --version=*) VERSION=${1#*=} ;;
    --dir) [ $# -ge 2 ] || fail "--dir needs a folder"; DIR=$2; shift ;;
    --dir=*) DIR=${1#*=} ;;
    --add-path) add_path=1 ;;
    --force) force=1 ;;
    --setup) setup=1 ;;
    --no-setup) setup=0 ;;
    --project) [ $# -ge 2 ] || fail "--project needs a folder"; project=$2; shift ;;
    --project=*) project=${1#*=} ;;
    --db) [ $# -ge 2 ] || fail "--db needs chronos or postgres"; db=$2; shift ;;
    --db=*) db=${1#*=} ;;
    --database-url) [ $# -ge 2 ] || fail "--database-url needs a URL"; db_url=$2; shift ;;
    --database-url=*) db_url=${1#*=} ;;
    --no-start) start_it=0 ;;
    --yes | -y) yes=1 ;;
    --quiet | -q) quiet=1 ;;
    --no-color) NO_COLOR=1 ;;
    --help | -h) usage; exit 0 ;;
    *) fail "unknown option '$1' (try --help)" ;;
    esac
    shift
done

case "$db" in '' | chronos | postgres) ;; *) fail "--db is chronos or postgres, not '$db'" ;; esac
[ -n "$db_url" ] && [ -z "$db" ] && db=postgres
case "$VERSION" in
latest | __*) rel=latest/download ref= ;;
*[!A-Za-z0-9._-]*) fail "FORKBASE_VERSION must be a release tag like v0.2.0, not '$VERSION'" ;;
*) rel="download/$VERSION" ref="refs/tags/$VERSION" ;;
esac
BASE="${FORKBASE_BASE_URL:-https://github.com/$REPO/releases/$rel}"
EBASE="${FORKBASE_ENGINE_BASE_URL:-https://github.com/$ENGINE_REPO/releases/download/$ENGINE_VERSION}"

setup_ui
started=$(now)

os=$(uname -s)
cpu=$(uname -m)
case "$os/$cpu" in
Darwin/arm64 | Darwin/aarch64) target=aarch64-apple-darwin where="macOS, Apple silicon" ;;
Darwin/x86_64) target=x86_64-apple-darwin where="macOS, Intel" ;;
Linux/x86_64 | Linux/amd64) target=x86_64-unknown-linux-musl where="Linux, x86-64" ;;
Linux/aarch64 | Linux/arm64) target=aarch64-unknown-linux-musl where="Linux, ARM64" ;;
*) fail "no prebuilt binary for $os $cpu yet: say which you need at https://github.com/$REPO/issues" ;;
esac

command -v curl >/dev/null || fail "needs curl"
if command -v sha256sum >/dev/null; then
    sha() { sha256sum "$1" | cut -d' ' -f1; }
elif command -v shasum >/dev/null; then
    sha() { shasum -a 256 "$1" | cut -d' ' -f1; }
else
    fail "needs sha256sum or shasum to check the downloads"
fi
command -v tar >/dev/null || fail "needs tar"

tmp=$(mktemp -d)
pid='' srv='' serving=''
trap 'cleanup' EXIT
trap 'interrupted' INT TERM

shown_version=${VERSION#v}
case "$shown_version" in latest | __*) shown_version="latest" ;; esac
title "Forkbase installer" "$shown_version"
step_ok "Platform" "$where ($target)"
step_ok "Install to" "$(tilde "$DIR")"

mkdir -p "$DIR" 2>/dev/null && [ -w "$DIR" ] ||
    fail "can't write to $DIR; set FORKBASE_INSTALL_DIR (or --dir) to a folder you can write (to use $DIR, run this script with sudo yourself)"

# the engine: asked when there is a person at a terminal and nobody said
if [ -z "$engine" ]; then
    if [ -x "$DIR/chronos" ]; then
        engine=1
        note "the Chronos engine is in $(tilde "$DIR"): it's checked and updated too (FORKBASE_ENGINE=0 to leave it)"
    elif ask "Also install the Chronos engine? Agents' worlds need it (about 20 MB)" y; then
        engine=1
    else
        engine=0
    fi
fi

install_one forkbase "$BASE" "$ref" "$VERSION" "Forkbase"
fb_line=$installed_line
if [ "$engine" = 1 ]; then
    install_one chronos "$EBASE" "refs/tags/$ENGINE_VERSION" "$ENGINE_VERSION" "Chronos engine"
    ch_line=$installed_line
else
    ch_line=
fi

# PATH: the folder may not be on it, and another forkbase may come first
path_hint=
case ":$PATH:" in
*":$DIR:"*)
    first=$(command -v forkbase 2>/dev/null || true)
    if [ -n "$first" ] && [ "$first" != "$DIR/forkbase" ]; then
        warn "another forkbase comes first on your PATH: $first (remove it, or put $(tilde "$DIR") before it)"
    fi
    ;;
*) add_to_path ;;
esac

took=$(( $(now) - started ))
if [ "$quiet" = 1 ]; then
    printf 'forkbase: installed %s in %s\n' "$fb_line" "$(tilde "$DIR")" >&2
    [ "$setup" = 1 ] || return 0
fi
say ""
say "  ${G}${B}Installed${R} ${D}in $(dur "$took")${R}"
say "    $fb_line"
[ -n "$ch_line" ] && say "    $ch_line"

# the project: asked when there is a person at a terminal; --yes alone sets nothing up
if [ -z "$setup" ]; then
    if [ "$yes" = 1 ]; then setup=0
    elif [ "$fancy" = 1 ] && say "" && ask "Set up a project now? It takes about a minute" y; then setup=1
    else setup=0; fi
fi
if [ "$setup" = 1 ]; then
    setup_project
    return 0
fi

say ""
say "  ${B}Next${R}"
[ -n "$path_hint" ] && say "    ${C}$path_hint${R}"
say "    ${C}mkdir myapp && cd myapp${R}"
if [ "$engine" = 1 ]; then
    say "    ${C}forkbase init --db chronos${R}       ${D}# or --db postgres --database-url ...${R}"
else
    say "    ${C}forkbase init --db postgres --database-url postgres://...${R}"
    say "    ${D}no engine: agents need it. Add it any time: rerun with FORKBASE_ENGINE=1${R}"
fi
say "    ${C}forkbase start${R}"
say "    ${D}or run the installer again and say yes to setting up a project${R}"
say ""
say "  ${D}Docs${R}  $DOCS"
say ""
}

# --- the project: folder, database, ports, init, start, keys, dashboard ----------------------------------------

setup_project() {
    section "Your project"
    fb="$DIR/forkbase"

    # where
    if [ -z "$project" ]; then
        def="$PWD/myapp"
        k=2
        while [ -e "$def" ] && [ ! -f "$def/forkbase.toml" ]; do def="$PWD/myapp-$k"; k=$((k + 1)); done
        while :; do
            project=$(full_path "$(prompt "Project folder" "$(tilde "$def")")")
            why=$(bad_folder "$project") || break
            warn "$why"
        done
    else
        project=$(full_path "$project")
        why=$(bad_folder "$project") && fail "--project $(tilde "$project"): $why"
    fi

    if [ -f "$project/forkbase.toml" ]; then
        step_ok "Folder" "$(tilde "$project") has a project already: using it as it is"
        db=$(awk -F'"' '/^mode *=/ { print $2; exit }' "$project/forkbase.toml")
    else
        if [ -e "$project" ] && [ -n "$(ls -A "$project" 2>/dev/null)" ]; then
            ask "$(tilde "$project") isn't empty. Put the project there anyway" n ||
                fail "stopped: pick another folder with --project, or run the installer again"
        fi
        mkdir -p "$project" || fail "can't make $project"

        # which database
        if [ -z "$db" ]; then
            db=$(choose "Database" \
                "chronos" "Built in: the Chronos engine, nothing else to run (best to start)" \
                "postgres" "Your own Postgres 16+ (local, RDS, Neon, Supabase...)")
        fi
        if [ "$db" = chronos ] && [ ! -x "$DIR/chronos" ]; then
            if ask "The built-in database is the Chronos engine. Install it now (about 20 MB)" y; then
                engine=1
                install_one chronos "$EBASE" "refs/tags/$ENGINE_VERSION" "$ENGINE_VERSION" "Chronos engine"
                section "Your project"
            else
                db=postgres
            fi
        fi
        if [ "$db" = postgres ] && [ -z "$db_url" ]; then
            db_url=$(prompt "Postgres URL" "postgres://postgres@127.0.0.1:5432/postgres")
        fi

        if [ "$db" = postgres ]; then
            (cd "$project" && "$fb" init --db postgres --database-url "$db_url") </dev/null >"$tmp/init.log" 2>&1 ||
                fail "forkbase init failed: $(tail -n 1 "$tmp/init.log")"
        else
            (cd "$project" && "$fb" init --db chronos) </dev/null >"$tmp/init.log" 2>&1 ||
                fail "forkbase init failed: $(tail -n 1 "$tmp/init.log")"
        fi
        case "$db" in
        chronos) step_ok "Database" "built in (the Chronos engine), kept in $(tilde "$project")/.forkbase" ;;
        *) step_ok "Database" "your Postgres: $(printf %s "$db_url" | sed 's#//\([^:/@]*\):[^@]*@#//\1:•••@#')" ;;
        esac

        # ports nobody else is using
        port=$(free_port 8000)
        if [ "$port" != 8000 ]; then
            sed "s/^listen = \"127.0.0.1:8000\"/listen = \"127.0.0.1:$port\"/" "$project/forkbase.toml" >"$tmp/t" &&
                cat "$tmp/t" >"$project/forkbase.toml"
            note "port 8000 is taken: Forkbase will listen on $port"
        fi
        if [ "$db" = chronos ] || [ "$engine" = 1 ]; then
            pg=$(free_port 54329)
            if [ "$pg" != 54329 ]; then
                sed "s/^pg_listen = \"127.0.0.1:54329\"/pg_listen = \"127.0.0.1:$pg\"/" "$project/forkbase.toml" >"$tmp/t" &&
                    cat "$tmp/t" >"$project/forkbase.toml"
            fi
        fi
        step_ok "Config" "$(tilde "$project")/forkbase.toml"
    fi
    port=$(awk -F'[":]' '/^listen *=/ { print $(NF-1); exit }' "$project/forkbase.toml")
    case "$port" in '' | *[!0-9]*) port=8000 ;; esac
    url="http://127.0.0.1:$port"

    if [ -z "$start_it" ]; then
        if ask "Start Forkbase now" y; then start_it=1; else start_it=0; fi
    fi
    if [ "$start_it" != 1 ]; then
        say ""
        say "  ${B}Next${R}"
        [ -n "$path_hint" ] && say "    ${C}$path_hint${R}"
        say "    ${C}cd $(tilde "$project") && forkbase start${R}"
        say "    ${D}then forkbase keys for the API keys, and the dashboard at $url/dashboard/${R}"
        say ""
        say "  ${D}Docs${R}  $DOCS"
        say ""
        return 0
    fi

    if curl -fsS -m 2 "$url/health" >/dev/null 2>&1; then
        fail "something already answers on $url: stop it, or set server.listen in $(tilde "$project")/forkbase.toml"
    fi
    mkdir -p "$project/.forkbase"
    log="$project/.forkbase/forkbase.log"
    # a forkbase with `start --background` keeps running after the installer ends (and the terminal closes)
    bg=
    "$fb" start --help 2>/dev/null | grep -q -- --background && bg=1
    if [ -n "$bg" ]; then
        (cd "$project" && exec "$fb" start --background) </dev/null >"$tmp/bgstart" 2>&1 &
        starter=$!
        srv=
    else
        (cd "$project" && exec "$fb" start) </dev/null >>"$log" 2>&1 &
        srv=$!
    fi
    spin_start "Starting Forkbase (the first start sets up the database)"
    waited=0
    until curl -fsS -m 2 "$url/health" >/dev/null 2>&1; do
        if [ -n "$bg" ] && ! kill -0 "$starter" 2>/dev/null; then
            wait "$starter" 2>/dev/null && continue
            spin_stop
            say ""
            { cat "$tmp/bgstart"; tail -n 8 "$log"; } 2>/dev/null | sed 's/^/    /' >&2
            fail "Forkbase stopped while starting (above: the end of $(tilde "$log")). Fix it, then: cd $(tilde "$project") && forkbase start --background"
        fi
        if [ -z "$bg" ] && ! kill -0 "$srv" 2>/dev/null; then
            spin_stop
            srv=
            say ""
            tail -n 8 "$log" | sed 's/^/    /' >&2
            fail "Forkbase stopped while starting (above: the end of $(tilde "$log")). Fix it, then: cd $(tilde "$project") && forkbase start"
        fi
        if [ "$waited" -ge 180 ]; then
            spin_stop
            fail "Forkbase didn't answer on $url within 3 minutes; see $(tilde "$log")"
        fi
        sleep 1
        waited=$((waited + 1))
    done
    spin_stop
    step_ok "Started" "$url ($(dur "$waited"))"
    owner_setup

    keys="$project/.forkbase/api-keys.json"
    k=0
    while [ ! -s "$keys" ] && [ "$k" -lt 10 ]; do sleep 1; k=$((k + 1)); done
    anon=$(json_field anon "$keys")

    say ""
    say "  ${G}${B}Forkbase is running${R} ${D}in $(tilde "$project") ($db mode)${R}"
    say ""
    say "    ${B}API${R}           $url"
    say "    ${B}Dashboard${R}     $url/dashboard/"
    if [ -n "$owner_email" ]; then
        say "    ${B}Sign in${R}       $owner_email ${D}and your password${R}"
    else
        say "    ${B}Sign in${R}       ${D}with the service key (forkbase keys), or make a sign-in:${R}"
        say "                  ${C}cd $(tilde "$project") && forkbase owner --email you@company.com${R}"
    fi
    say "    ${B}anon key${R}      ${D}$anon${R}"
    say "                  ${D}safe in a browser or app: row-level security limits it${R}"
    say "    ${B}service key${R}   ${D}forkbase keys prints it: full access, for your servers only${R}"
    say ""
    if ask "Open the dashboard in your browser" y; then
        if command -v open >/dev/null 2>&1; then open "$url/dashboard/" >/dev/null 2>&1 || true
        elif command -v xdg-open >/dev/null 2>&1; then xdg-open "$url/dashboard/" >/dev/null 2>&1 || true
        else note "open $url/dashboard/ in your browser"; fi
    fi
    say ""
    say "  ${B}Try it${R}"
    say "    ${C}curl $url/rest/v1/ -H \"apikey: \$ANON\"${R}   ${D}# ANON: the anon key above${R}"
    say "    ${D}make a table in the dashboard (Table editor), or with SQL in its SQL page${R}"
    say "    ${D}your first agent run: $DOCS#5-run-an-agent${R}"
    say ""
    say "  ${B}Later${R}"
    [ -n "$path_hint" ] && say "    ${C}$path_hint${R}"
    if [ -n "$bg" ]; then
        say "    ${C}cd $(tilde "$project")${R}"
        say "    ${C}forkbase stop${R}                    ${D}# stop it${R}"
        say "    ${C}forkbase start --background${R}      ${D}# start it again${R}"
        say "    ${C}forkbase keys${R}                    ${D}# print the keys${R}"
        say "    ${C}forkbase uninstall${R}               ${D}# remove Forkbase (add --purge to delete this project too)${R}"
        say ""
        say "  ${G}${OK}${R} Forkbase keeps running in the background, also after you close this terminal. ${D}Logs: $(tilde "$log")${R}"
        say ""
        return 0
    fi
    say "    ${C}cd $(tilde "$project") && forkbase start${R}   ${D}# start it again${R}"
    say "    ${C}forkbase keys${R}                    ${D}# print the keys${R}"
    say ""
    say "  ${D}Logs in $(tilde "$log"). Forkbase runs while this stays open: press Ctrl-C to stop it.${R}"
    serving=1
    [ "$fancy" = 1 ] && printf '\033[?25h' >&2
    rc=0
    wait "$srv" || rc=$?
    srv=
    serving=
    [ "$rc" = 0 ] || fail "Forkbase stopped (exit $rc); see $(tilde "$log")"
}

# owner_setup: the dashboard's sign-in (an email and a password, an admin), made with `forkbase owner`; then, only if
# the person agrees, that email to the Forkbase team. The password goes to forkbase on stdin, never on a command line,
# and stays in this project's database as an Argon2 hash.
owner_setup() {
    owner_email=${owner_email:-${FORKBASE_OWNER_EMAIL:-}}
    owner_pw=${FORKBASE_OWNER_PASSWORD:-}
    if ! "$fb" owner --help >/dev/null 2>&1; then
        owner_email=
        return 0
    fi
    if [ -z "$owner_email" ] && can_ask; then
        say ""
        say "  ${B}Your dashboard sign-in${R}"
        note "an email and a password, kept only in this project's database"
        while :; do
            owner_email=$(prompt "Email" "")
            good_email "$owner_email" && break
            warn "the dashboard signs in with an email address: type one"
        done
    fi
    if [ -z "$owner_email" ]; then
        # no terminal to ask in: FORKBASE_OWNER_EMAIL and FORKBASE_OWNER_PASSWORD (or --email) make the sign-in
        step_skip "Sign-in" "none made (no terminal; set FORKBASE_OWNER_EMAIL and FORKBASE_OWNER_PASSWORD); later: forkbase owner --email you@company.com"
        return 0
    fi
    good_email "$owner_email" || fail "--email: '$owner_email' is not an email address"
    owner_email=$(printf '%s' "$owner_email" | tr '[:upper:]' '[:lower:]')
    if [ -z "$owner_pw" ]; then
        if ! can_ask; then
            step_skip "Sign-in" "no password (set FORKBASE_OWNER_PASSWORD); later: forkbase owner --email $owner_email"
            owner_email=
            return 0
        fi
        while :; do
            p1=$(secret "Password (8 or more characters)")
            if [ "${#p1}" -lt 8 ]; then
                warn "at least 8 characters"
                continue
            fi
            p2=$(secret "The same password again")
            [ "$p1" = "$p2" ] && break
            warn "those two didn't match: once more"
        done
        owner_pw=$p1
        p1='' p2=''
    fi
    [ "${#owner_pw}" -ge 8 ] || fail "the password needs 8 or more characters"
    if out=$(printf '%s\n' "$owner_pw" | (cd "$project" && "$fb" owner --email "$owner_email") 2>&1); then
        step_ok "Sign-in" "$owner_email, an admin"
    else
        warn "couldn't make the sign-in: $(printf '%s' "$out" | tail -n 1)"
        owner_email=
    fi
    owner_pw=''
    [ -n "$owner_email" ] && share_email
    return 0
}

# share_email: with the person's yes (or FORKBASE_SHARE_EMAIL=1), tell the Forkbase team who set Forkbase up, so they
# can ask how it went. Sent: the email, OS, CPU, version and database mode. Never the password, keys or data.
share_email() {
    case "${share:-}" in
    1) ;;
    0) return 0 ;;
    *)
        can_ask || return 0
        say ""
        note "May the Forkbase team email you? To ask how setup went, and about big releases. No spam, no sharing."
        note "Sent: this address, your OS, Forkbase version and database mode. Never your password, keys or data."
        if ! ask "Share $owner_email with the Forkbase team" y; then
            step_skip "Shared" "nothing sent"
            return 0
        fi
        ;;
    esac
    body=$(printf '{"email":"%s","os":"%s","arch":"%s","version":"%s","db":"%s","source":"installer"}' \
        "$(json_esc "$owner_email")" "$(json_esc "$os")" "$(json_esc "$(uname -m)")" "$(json_esc "$shown_version")" "$(json_esc "$db")")
    if curl -fsS -m 8 -X POST -H 'content-type: application/json' --data "$body" "$CONTACT_URL" >/dev/null 2>&1; then
        step_ok "Shared" "thanks: we'll write to $owner_email"
    else
        step_skip "Shared" "couldn't reach $(printf '%s' "$CONTACT_URL" | sed 's|^[a-z]*://||; s|/.*||'); nothing sent"
    fi
}

good_email() {
    case "$1" in *[[:space:]]* | *@*@* | @* | *@ | *@.* | *. ) return 1 ;; ?*@?*.?*) return 0 ;; *) return 1 ;; esac
}
json_esc() { printf '%s' "$1" | sed 's/[\\"]/\\&/g' | tr -d '\000-\037'; }

# can_ask: a person is at a terminal to answer
can_ask() { [ "$yes" != 1 ] && [ "$quiet" != 1 ] && [ "$fancy" = 1 ] && { : </dev/tty; } 2>/dev/null; }

# secret <question>: a line typed without being shown
secret() {
    printf '\033[?25h  %s?%s %s ' "$C" "$R" "$1" >&2
    saved=$(stty -g </dev/tty 2>/dev/null) || saved=
    stty -echo </dev/tty 2>/dev/null || true
    answer=
    IFS= read -r answer </dev/tty || answer=
    if [ -n "$saved" ]; then stty "$saved" </dev/tty 2>/dev/null || stty echo </dev/tty 2>/dev/null; else stty echo </dev/tty 2>/dev/null; fi
    printf '\n\033[?25l' >&2
    printf '%s' "$answer"
}

# free_port <first>: the first of the next 20 ports nothing on this machine answers on
free_port() {
    fp=$1
    while [ "$fp" -lt $(($1 + 20)) ]; do
        rc=0
        curl -s -m 1 -o /dev/null "http://127.0.0.1:$fp/" 2>/dev/null || rc=$?
        [ "$rc" = 7 ] && { echo "$fp"; return 0; }
        fp=$((fp + 1))
    done
    echo "$1"
}

json_field() { tr -d '\n' <"$2" 2>/dev/null | sed -n "s/.*\"$1\"[[:space:]]*:[[:space:]]*\"\([^\"]*\)\".*/\1/p"; }

# --- one binary: download, check, test-run, put in place --------------------------------------------------------

# install_one <name> <base url> <tag ref or empty> <tag> <label>; sets installed_line
install_one() {
    n=$1 base=$2 tref=$3 tag=$4 label=$5
    file="$n-$target.tar.gz"
    want_v=${tag#v}
    have=
    if [ -x "$DIR/$n" ]; then
        have=$("$DIR/$n" --version 2>/dev/null | awk '{print $2}') || have=
    fi
    section "$label"
    if [ -n "$tref" ] && [ -n "$have" ] && [ "$have" = "$want_v" ] && [ "$force" != 1 ]; then
        step_ok "Up to date" "$n $have is already in $(tilde "$DIR") (--force to reinstall)"
        installed_line=$(row "$n" "$have" "$DIR/$n" "kept")
        return 0
    fi

    download "$base/$file" "$tmp/$file" "$n" || dl_fail "$base/$file"
    download "$base/SHA256SUMS" "$tmp/$n.SHA256SUMS" "checksums" small || dl_fail "$base/SHA256SUMS"

    want=$(awk -v f="$file" '$2 == f { print $1 }' "$tmp/$n.SHA256SUMS")
    [ -n "$want" ] || fail "SHA256SUMS has no entry for $file; nothing was installed"
    got=$(sha "$tmp/$file")
    [ "$got" = "$want" ] || fail "checksum mismatch for $file (expected $want, got $got): the download is not the release's; nothing was installed"
    step_ok "Checksum" "sha256 $(echo "$got" | cut -c1-12)… matches the release"

    verify="${FORKBASE_VERIFY:-}"
    if [ "$verify" = 0 ]; then
        step_skip "Signature" "not checked: FORKBASE_VERIFY=0 (the checksum was)"
    elif [ "$verify" != 1 ] && ! command -v cosign >/dev/null; then
        step_skip "Signature" "not checked: install cosign to check it too (the checksum was)"
    else
        command -v cosign >/dev/null || fail "FORKBASE_VERIFY=1 needs cosign: https://docs.sigstore.dev/cosign/system_config/installation/"
        download "$base/$file.sigstore.json" "$tmp/$file.sigstore.json" "signature" small || dl_fail "$base/$file.sigstore.json"
        spin_start "Checking the Sigstore signature"
        if cosign verify-blob --bundle "$tmp/$file.sigstore.json" --certificate-identity "$SIGNER_ACCOUNT" \
            --certificate-oidc-issuer https://accounts.google.com "$tmp/$file" >/dev/null 2>&1; then
            spin_stop
            step_ok "Signature" "built and signed by 2090 Labs' release builds (Sigstore)"
        else
            spin_stop
            fail "$file has no valid signature from 2090 Labs' release builds; nothing was installed"
        fi
    fi

    mkdir -p "$tmp/$n.x"
    tar -xzf "$tmp/$file" -C "$tmp/$n.x" || fail "$file would not unpack; nothing was installed"
    [ -f "$tmp/$n.x/$n" ] || fail "$file has no $n binary in it; nothing was installed"
    chmod +x "$tmp/$n.x/$n"
    # it runs here before anything is put in place
    v=$("$tmp/$n.x/$n" --version 2>/dev/null) || fail "the $target build of $n doesn't run on this machine; nothing was installed"
    # and it is the release asked for
    if [ -n "$tref" ] && [ "$v" != "$n $want_v" ]; then
        fail "asked for $tag but the build says '$v'; nothing was installed"
    fi
    step_ok "Runs" "$v"

    # copy next to the target, then rename: a same-directory mv is atomic, so an interrupted install never leaves a
    # half-written binary
    cp "$tmp/$n.x/$n" "$DIR/.$n.tmp.$$"
    chmod +x "$DIR/.$n.tmp.$$"
    mv -f "$DIR/.$n.tmp.$$" "$DIR/$n"
    nv=${v#"$n "}
    if [ -z "$have" ]; then what="installed"
    elif [ "$have" = "$nv" ]; then what="reinstalled"
    else what="updated from $have"; fi
    step_ok "Installed" "$(tilde "$DIR/$n") ($what)"
    installed_line=$(row "$n" "$nv" "$DIR/$n" "$what")
}

row() { printf '%s%-9s%s %-8s %s%s%s' "$B" "$1" "$R" "$2" "$D" "$(tilde "$3")" "$R"; }

dl_fail() {
    msg=$(tail -n 1 "$tmp/err" 2>/dev/null | sed 's/^curl: ([0-9]*) //')
    fail "could not download $1${msg:+ ($msg)}. Check your connection (a proxy needs HTTPS_PROXY), then run the installer again: nothing was installed"
}

# --- downloads with a live progress line ---------------------------------------------------------------------------

# download <url> <file> <label> [small]: retries a failed or stalled transfer (under 2 KB/s for 30 s) up to 4 times,
# resuming where it stopped
download() {
    url=$1 out=$2 dlabel=$3 small=${4:-}
    attempt=1
    rm -f "$out"
    while :; do
        : >"$tmp/h"
        : >"$tmp/err"
        t0=$(now)
        rc=0
        if [ "$fancy" = 1 ] && [ -z "$small" ]; then
            curl -fsSL --connect-timeout 20 --speed-limit 2048 --speed-time 30 -C - -D "$tmp/h" -o "$out" "$url" \
                </dev/null 2>"$tmp/err" &
            pid=$!
            watch "$pid" "$out" "$dlabel" "$url"
            wait "$pid" || rc=$?
            pid=
            clear_line
        else
            [ -n "$small" ] || say_plain "  downloading $dlabel: $url"
            [ -n "$small" ] && [ "$fancy" = 1 ] && spin_start "Fetching $dlabel"
            curl -fsSL --connect-timeout 20 --speed-limit 2048 --speed-time 30 -C - -o "$out" "$url" \
                </dev/null 2>"$tmp/err" || rc=$?
            [ -n "$small" ] && [ "$fancy" = 1 ] && spin_stop
        fi
        if [ "$rc" = 0 ]; then
            if [ -z "$small" ]; then
                size=$(fsize "$out")
                secs=$(( $(now) - t0 ))
                step_ok "Downloaded" "$dlabel, $(hbytes "$size") in $(dur "$secs")$(rate "$size" "$secs")"
            fi
            return 0
        fi
        # a missing file (HTTP 404) won't appear on a retry
        if [ "$rc" = 22 ] && grep -q ' 404' "$tmp/err" 2>/dev/null; then return 1; fi
        [ "$attempt" -ge 4 ] && return 1
        why=$(tail -n 1 "$tmp/err" 2>/dev/null | sed 's/^curl: ([0-9]*) //')
        [ "$rc" = 28 ] && why="the connection stalled"
        warn "$dlabel: ${why:-download failed (curl $rc)}; resuming in $((attempt * 2)) s (try $((attempt + 1)) of 4)"
        sleep $((attempt * 2))
        attempt=$((attempt + 1))
    done
}

# watch <pid> <file> <label> <url>: redraws the progress line until curl exits
watch() {
    wpid=$1 wfile=$2 wlabel=$3 host=$(printf %s "$4" | sed 's#^[a-z]*://##; s#/.*##')
    wstart=$(now) first='' b0=0 total='' frame=0
    while kill -0 "$wpid" 2>/dev/null; do
        bytes=$(fsize "$wfile")
        t=$(now)
        if [ -z "$total" ]; then
            total=$(content_total "$tmp/h")
            # after a redirect the bytes come from the release's file host
            h2=$(awk 'tolower($1) == "location:" { sub(/^[a-zA-Z]*:\/\//, "", $2); sub(/\/.*/, "", $2); h = $2 } END { print h }' "$tmp/h" | tr -d '\r')
            [ -n "$h2" ] && host=$h2
        fi
        if [ "$bytes" -le 0 ] && [ -z "$first" ]; then
            draw "$(spin_frame "$frame") ${wlabel}: connecting to ${host}… $(dur $((t - wstart)))"
        else
            [ -n "$first" ] || { first=$t; b0=$bytes; }
            draw "$(bar_line "$wlabel" "$bytes" "${total:-0}" $((t - first)) $((bytes - b0)) "$frame")"
        fi
        frame=$((frame + 1))
        sleep 0.2 2>/dev/null || sleep 1
    done
}

# the full size, from the last response's headers: Content-Range's total (a resumed download), else Content-Length
content_total() {
    tr -d '\r' <"$1" 2>/dev/null | awk '
        /^HTTP\// { ok = ($2 == 200 || $2 == 206); len = ""; range = "" }
        tolower($1) == "content-length:" { len = $2 }
        tolower($1) == "content-range:" { n = split($3, a, "/"); range = a[n] }
        END { if (ok) { if (range != "" && range != "*") print range; else if (len != "") print len } }'
}

bar_line() {
    awk -v l="$1" -v b="$2" -v t="$3" -v e="$4" -v d="$5" -v w="$barw" -v u="$utf" -v f="$6" \
        -v on="$G" -v off="$D" -v r="$R" '
    function h(x) { if (x >= 1048576) return sprintf("%.1f MB", x / 1048576); if (x >= 1024) return sprintf("%d KB", x / 1024); return sprintf("%d B", x) }
    BEGIN {
        s = (e > 0) ? d / e : 0
        line = "  " l " "
        if (t > 0) {
            n = int(b * w / t); if (n > w) n = w
            full = ""; empty = ""
            for (i = 0; i < n; i++) full = full (u ? "█" : "#")
            for (; i < w; i++) empty = empty (u ? "░" : "-")
            line = line on full r off empty r sprintf(" %3d%%  %s / %s", int(b * 100 / t), h(b), h(t))
            if (s > 0) { left = int((t - b) / s); line = line sprintf("  %s/s  ", h(s)) (left >= 60 ? sprintf("%dm %02ds", left / 60, left % 60) : left "s") " left" }
        } else {
            line = line h(b)
            if (s > 0) line = line sprintf("  %s/s", h(s))
        }
        printf "%s", line
    }'
}

# --- small spinner for steps without a size ---------------------------------------------------------------------

spin_start() {
    [ "$fancy" = 1 ] || return 0
    (
        i=0 s0=$(now)
        while :; do
            draw "$(spin_frame "$i") $1… $(dur $(( $(now) - s0 )))"
            i=$((i + 1))
            sleep 0.2 2>/dev/null || sleep 1
        done
    ) </dev/null &
    spid=$!
}
spin_stop() {
    [ -n "${spid:-}" ] || return 0
    kill "$spid" 2>/dev/null || true
    wait "$spid" 2>/dev/null || true
    spid=
    clear_line
}
spin_frame() {
    if [ "$utf" = 1 ]; then
        set -- "$1" ⠋ ⠙ ⠹ ⠸ ⠼ ⠴ ⠦ ⠧ ⠇ ⠏
        k=$(( $1 % 10 + 2 ))
    else
        set -- "$1" '|' '/' '-' "\\"
        k=$(( $1 % 4 + 2 ))
    fi
    eval "printf '  %s%s%s' \"\$C\" \"\${$k}\" \"\$R\""
}

# --- PATH --------------------------------------------------------------------------------------------------------

add_to_path() {
    sh_name=$(basename "${SHELL:-sh}")
    case "$sh_name" in
    zsh) rc="${ZDOTDIR:-$HOME}/.zshrc" line="export PATH=\"$DIR:\$PATH\"" ;;
    bash) if [ "$os" = Darwin ]; then rc="$HOME/.bash_profile"; else rc="$HOME/.bashrc"; fi; line="export PATH=\"$DIR:\$PATH\"" ;;
    fish) rc="$HOME/.config/fish/config.fish" line="fish_add_path \"$DIR\"" ;;
    *) rc="$HOME/.profile" line="export PATH=\"$DIR:\$PATH\"" ;;
    esac
    if [ -f "$rc" ] && grep -qF "$DIR" "$rc" 2>/dev/null; then
        path_hint="exec $sh_name    # $(tilde "$rc") adds $(tilde "$DIR") to PATH: open a new shell"
        return 0
    fi
    # a shell's startup file changes only when someone says so: never by default without a person to ask
    if [ -z "$add_path" ] && { [ "$yes" = 1 ] || [ "$fancy" != 1 ]; }; then add_path=0; fi
    if [ -z "$add_path" ]; then
        if ask "$(tilde "$DIR") isn't on your PATH. Add it in $(tilde "$rc")" y; then add_path=1; else add_path=0; fi
    fi
    if [ "$add_path" = 1 ]; then
        mkdir -p "$(dirname "$rc")"
        printf '\n# added by the Forkbase installer\n%s\n' "$line" >>"$rc"
        step_ok "PATH" "added $(tilde "$DIR") in $(tilde "$rc")"
        path_hint="exec $sh_name    # open a new shell so PATH has it"
    else
        path_hint="$line"
        note "$(tilde "$DIR") isn't on your PATH: add this line to $(tilde "$rc")"
    fi
}

# --- output ------------------------------------------------------------------------------------------------------

setup_ui() {
    fancy=0 utf=0 G='' Y='' C='' D='' B='' R='' RED=''
    if [ -t 2 ] && [ "$quiet" != 1 ] && [ "${TERM:-dumb}" != dumb ]; then fancy=1; fi
    case "${LC_ALL:-${LC_CTYPE:-${LANG:-}}}" in *UTF-8* | *utf-8* | *UTF8* | *utf8*) utf=1 ;; esac
    if [ "$fancy" = 1 ] && [ -z "${NO_COLOR:-}" ]; then
        e=$(printf '\033')
        G="${e}[32m" Y="${e}[33m" C="${e}[36m" D="${e}[2m" B="${e}[1m" R="${e}[0m" RED="${e}[31m"
    fi
    cols=$( { stty size </dev/tty; } 2>/dev/null | awk '{ print $2 }')
    case "$cols" in '' | *[!0-9]*) cols=80 ;; esac
    barw=$((cols - 62))
    [ "$barw" -gt 30 ] && barw=30
    [ "$barw" -lt 10 ] && barw=10
    if [ "$utf" = 1 ]; then OK="✓" SKIP="–" WARN="!" BAD="✗"; else OK="ok" SKIP="--" WARN="!" BAD="x"; fi
    [ "$fancy" = 1 ] && printf '\033[?25l' >&2
    return 0
}

now() { date +%s; }
fsize() { if [ -f "$1" ]; then wc -c <"$1" | tr -d ' '; else echo 0; fi; }
# shellcheck disable=SC2088 # a ~ to read, not to expand
tilde() { case "$1" in "$HOME") printf "~" ;; "$HOME"/*) printf '~/%s' "${1#"$HOME"/}" ;; *) printf %s "$1" ;; esac; }
hbytes() { awk -v x="$1" 'BEGIN { if (x >= 1048576) printf "%.1f MB", x / 1048576; else if (x >= 1024) printf "%d KB", x / 1024; else printf "%d B", x }'; }
rate() { [ "$2" -gt 0 ] && awk -v b="$1" -v s="$2" 'BEGIN { x = b / s; if (x >= 1048576) printf ", %.1f MB/s", x / 1048576; else printf ", %d KB/s", x / 1024 }'; return 0; }
dur() { if [ "$1" -ge 60 ]; then printf '%dm %02ds' $(($1 / 60)) $(($1 % 60)); else printf '%ds' "$1"; fi; }

say() { [ "$quiet" = 1 ] || printf '%s\n' "$1" >&2; }
say_plain() { [ "$fancy" = 1 ] || say "$1"; }
draw() { printf '\r\033[K%s' "$1" >&2; }
clear_line() { [ "$fancy" = 1 ] && printf '\r\033[K' >&2; return 0; }
title() { say ""; say "  ${B}$1${R} ${D}$2${R}"; say ""; }
section() { say ""; say "  ${B}$1${R}"; }
step_ok() { say "  ${G}${OK}${R} $(printf '%-11s' "$1") ${D}$2${R}"; }
step_skip() { say "  ${D}${SKIP} $(printf '%-11s' "$1") $2${R}"; }
note() { say "  ${D}$1${R}"; }
warn() { [ "$quiet" = 1 ] || printf '  %s%s%s %s\n' "$Y" "$WARN" "$R" "$1" >&2; }

usage() {
    sed -n '2,28p' "$0" 2>/dev/null | sed 's/^# \{0,1\}//' ||
        echo "Forkbase installer: see https://github.com/2090-labs/forkbase/blob/main/docs/self-hosting.md"
}

# ask <question> <y|n>: a yes or no from the person at the terminal (the script itself may be stdin); the default
# when nobody can answer
ask() {
    if [ "$yes" = 1 ] || [ "$quiet" = 1 ] || [ "$fancy" != 1 ] || ! { : </dev/tty; } 2>/dev/null; then
        [ "$2" = y ]
        return
    fi
    if [ "$2" = y ]; then hint="[Y/n]"; else hint="[y/N]"; fi
    printf '\033[?25h  %s?%s %s %s ' "$C" "$R" "$1" "$D$hint$R" >&2
    answer=
    read -r answer </dev/tty || answer=
    printf '\033[?25l' >&2
    case "$answer" in
    [Yy]*) return 0 ;;
    [Nn]*) return 1 ;;
    *) [ "$2" = y ] ;;
    esac
}

# full_path <folder>: the folder as an absolute path, with ~ and a leading ./ expanded and no trailing /
full_path() {
    p=$1
    case "$p" in "~"/*) p="$HOME/${p#"~"/}" ;; "~") p=$HOME ;; /*) ;; *) p="$PWD/$p" ;; esac
    while :; do case "$p" in "$PWD/./"*) p="$PWD/${p#"$PWD/./"}" ;; *) break ;; esac; done
    while :; do case "$p" in */) p=${p%/} ;; *) break ;; esac; done
    printf '%s' "${p:-/}"
}

# bad_folder <absolute path>: why it can't hold a project (and success), or nothing (and failure) when it can. A
# stray key at the folder prompt (a \ or a space) must not become the project's folder.
bad_folder() {
    case "$1" in
    / | "$HOME") echo "pick a folder of its own, not $(tilde "$1")" ;;
    *) name=${1##*/}
       case "$name" in
       [A-Za-z0-9]*) case "$name" in *[!A-Za-z0-9._\ -]*) ;; *) return 1 ;; esac ;;
       esac
       echo "\"$name\" isn't a usable folder name: use letters, digits, . _ - or spaces, starting with a letter or digit" ;;
    esac
}

# prompt <question> <default>: a line from the person at the terminal, or the default
prompt() {
    if [ "$yes" = 1 ] || [ "$fancy" != 1 ] || ! { : </dev/tty; } 2>/dev/null; then
        printf '%s' "$2"
        return 0
    fi
    if [ -n "$2" ]; then printf '\033[?25h  %s?%s %s %s ' "$C" "$R" "$1" "$D($2)$R" >&2; else printf '\033[?25h  %s?%s %s ' "$C" "$R" "$1" >&2; fi
    answer=
    read -r answer </dev/tty || answer=
    printf '\033[?25l' >&2
    printf '%s' "${answer:-$2}"
}

# choose <question> <value> <label> [<value> <label>...]: one of the values; the first is the default
choose() {
    q=$1
    shift
    if [ "$yes" = 1 ] || [ "$fancy" != 1 ] || ! { : </dev/tty; } 2>/dev/null; then
        printf '%s' "$1"
        return 0
    fi
    printf '  %s?%s %s\n' "$C" "$R" "$q" >&2
    i=1
    while [ $# -ge 2 ]; do
        printf '    %s%d%s  %s\n' "$B" "$i" "$R" "$2" >&2
        eval "v_$i=\$1"
        i=$((i + 1))
        shift 2
    done
    printf '\033[?25h    %s%s%s ' "$D" "choose 1-$((i - 1)) (1)" "$R" >&2
    answer=
    read -r answer </dev/tty || answer=
    printf '\033[?25l' >&2
    case "$answer" in '' | *[!0-9]*) answer=1 ;; esac
    [ "$answer" -ge 1 ] && [ "$answer" -lt "$i" ] || answer=1
    eval "printf '%s' \"\$v_$answer\""
}

cleanup() {
    if [ -n "${srv:-}" ]; then kill "$srv" 2>/dev/null; wait "$srv" 2>/dev/null || true; fi
    [ -n "${pid:-}" ] && kill "$pid" 2>/dev/null
    [ -n "${spid:-}" ] && kill "$spid" 2>/dev/null
    [ "${fancy:-0}" = 1 ] && { printf '\r\033[K\033[?25h' >&2; stty echo </dev/tty 2>/dev/null; }
    [ -n "${tmp:-}" ] && rm -rf "$tmp"
    rm -f "${DIR:-/nonexistent}/.forkbase.tmp.$$" "${DIR:-/nonexistent}/.chronos.tmp.$$"
    return 0
}

interrupted() {
    if [ -n "${serving:-}" ]; then
        printf '\r\033[K  stopping Forkbase…\n' >&2
        cleanup
        printf '  stopped. Start it again: cd %s && forkbase start\n' "$(tilde "$project")" >&2
        trap - EXIT
        exit 0
    fi
    cleanup
    printf '\n  forkbase install: stopped; nothing half-installed was left behind\n' >&2
    trap - EXIT
    exit 130
}

fail() {
    [ "${fancy:-0}" = 1 ] && printf '\r\033[K' >&2
    printf '  %s%s forkbase install:%s %s\n' "${RED:-}" "${BAD:-x}" "${R:-}" "$*" >&2
    exit 1
}

main "$@"
