#!/bin/sh
# cobalt769 installer
#
#   curl -fsSL https://cobalt769.org/install.sh | sh
#   curl -fsSL https://cobalt769.org/install.sh | sh -s -- --prefix /opt/cobalt769 --version 1.2.3
#
# Downloads a prebuilt cobalt769 release tarball plus SHA256SUMS.txt, verifies
# the SHA-256 checksum (hard failure on mismatch), and installs:
#
#   $PREFIX/bin/cobalt769
#   $PREFIX/lib/libcobalt769_ffi.so      (libcobalt769_ffi.dylib on macOS)
#   $PREFIX/lib/libcobalt769_ffi.a
#   $PREFIX/include/cobalt769.h
#   $PREFIX/share/cobalt769/python/cobalt769.py

set -eu
umask 022

# ---------------------------------------------------------------------------
# Constants
# ---------------------------------------------------------------------------
PROJECT="cobalt769"
CF_RELEASES="https://cobalt769.org/releases"
GH_REPO="https://github.com/chai1any/cobalt-infra"
SUMS_FILE="SHA256SUMS.txt"

# ---------------------------------------------------------------------------
# Defaults
# ---------------------------------------------------------------------------
PREFIX="${HOME:?HOME is not set}/.local"
VERSION="latest"
BASE_URL_OPT=""
SOURCE="auto"   # auto | cloudflare | github

# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
say()  { printf '%s\n' "$*" >&2; }
info() { printf '==> %s\n' "$*" >&2; }
warn() { printf 'warning: %s\n' "$*" >&2; }
die()  { printf 'error: %s\n' "$*" >&2; exit 1; }
have() { command -v "$1" >/dev/null 2>&1; }

usage() {
    cat <<EOF
cobalt769 installer

Usage: install.sh [OPTIONS]

Options:
  --prefix DIR      Install prefix (default: \$HOME/.local)
  --version VER     Release version to install (default: latest)
  --base-url URL    Download base URL containing the tarball and ${SUMS_FILE}
                    (default: \$COBALT769_BASE_URL, else ${CF_RELEASES}/<version>,
                    falling back to GitHub Releases)
  --source SRC      Release source: auto (default), cloudflare, github
  -h, --help        Show this help and exit

Environment:
  COBALT769_BASE_URL   Same as --base-url (the flag takes precedence)

Examples:
  curl -fsSL https://cobalt769.org/install.sh | sh
  curl -fsSL https://cobalt769.org/install.sh | sh -s -- --prefix /opt/cobalt769
  curl -fsSL https://cobalt769.org/install.sh | sh -s -- --version 1.2.3 --source github
EOF
}

need_arg() {
    # $1 = flag name, $2 = number of remaining args (including the flag)
    [ "$2" -ge 2 ] || die "option '$1' requires an argument (see --help)"
}

# ---------------------------------------------------------------------------
# Argument parsing
# ---------------------------------------------------------------------------
while [ $# -gt 0 ]; do
    case "$1" in
        --prefix)       need_arg "$1" $#; PREFIX="$2"; shift 2 ;;
        --prefix=*)     PREFIX="${1#*=}"; shift ;;
        --version)      need_arg "$1" $#; VERSION="$2"; shift 2 ;;
        --version=*)    VERSION="${1#*=}"; shift ;;
        --base-url)     need_arg "$1" $#; BASE_URL_OPT="$2"; shift 2 ;;
        --base-url=*)   BASE_URL_OPT="${1#*=}"; shift ;;
        --source)       need_arg "$1" $#; SOURCE="$2"; shift 2 ;;
        --source=*)     SOURCE="${1#*=}"; shift ;;
        -h|--help)      usage; exit 0 ;;
        --)             shift; break ;;
        *)              die "unknown option: $1 (see --help)" ;;
    esac
done

[ -n "$PREFIX" ]  || die "--prefix must not be empty"
[ -n "$VERSION" ] || die "--version must not be empty"

case "$VERSION" in
    *[!A-Za-z0-9._+-]*) die "invalid version string: '$VERSION'" ;;
esac

case "$SOURCE" in
    auto|cloudflare|github) ;;
    *) die "invalid --source '$SOURCE' (expected: auto, cloudflare, github)" ;;
esac

# Make PREFIX absolute so printed paths and PATH hints are accurate.
case "$PREFIX" in
    /*) ;;
    *)  PREFIX="$(pwd)/$PREFIX" ;;
esac
PREFIX="${PREFIX%/}"
[ -n "$PREFIX" ] || PREFIX="/"

# ---------------------------------------------------------------------------
# Platform detection
# ---------------------------------------------------------------------------
uname_s="$(uname -s 2>/dev/null || echo unknown)"
uname_m="$(uname -m 2>/dev/null || echo unknown)"

case "$uname_s" in
    Linux)  OS="linux" ;;
    Darwin) OS="darwin" ;;
    *)      OS="unsupported" ;;
esac

case "$uname_m" in
    x86_64|amd64)  ARCH="x86_64" ;;
    aarch64|arm64) ARCH="aarch64" ;;
    *)             ARCH="unsupported" ;;
esac

if [ "$OS" = "darwin" ]; then
    SO_NAME="libcobalt769_ffi.dylib"
else
    SO_NAME="libcobalt769_ffi.so"
fi

TARBALL="${PROJECT}-${OS}-${ARCH}.tar.gz"

source_build_hint() {
    if [ "$VERSION" = "latest" ]; then
        tag_arg=""
    else
        tag_arg=" --tag v${VERSION#v}"
    fi
    say "No prebuilt ${PROJECT} binary for ${uname_s}/${uname_m}; build from source instead:"
    say "  cargo install --locked --git https://github.com/chai1any/cobalt769${tag_arg} --root \"${PREFIX}\" ${PROJECT}"
    exit 1
}

if [ "$OS" = "unsupported" ] || [ "$ARCH" = "unsupported" ]; then
    source_build_hint
fi

# ---------------------------------------------------------------------------
# Tool checks
# ---------------------------------------------------------------------------
if have curl; then
    DOWNLOADER="curl"
elif have wget; then
    DOWNLOADER="wget"
else
    die "need 'curl' or 'wget' to download releases"
fi

if have sha256sum; then
    SHA_TOOL="sha256sum"
elif have shasum; then
    SHA_TOOL="shasum"
else
    die "need 'sha256sum' or 'shasum' to verify downloads"
fi

for tool in tar gzip awk find mktemp; do
    have "$tool" || die "required tool not found: $tool"
done

sha256_of() {
    if [ "$SHA_TOOL" = "sha256sum" ]; then
        sha256sum "$1" | awk '{print $1}'
    else
        shasum -a 256 "$1" | awk '{print $1}'
    fi
}

# http_get URL OUTFILE
# Sets HTTP_CODE (000 on network failure / unknown). Returns 0 only on HTTP 200.
HTTP_CODE="000"
http_get() {
    _url="$1"
    _out="$2"
    rm -f "$_out"
    HTTP_CODE="000"
    if [ "$DOWNLOADER" = "curl" ]; then
        case "$_url" in
            https://*)
                HTTP_CODE="$(curl -sSL --proto '=https' --proto-redir '=https' --tlsv1.2 \
                    --retry 3 --connect-timeout 15 \
                    -o "$_out" -w '%{http_code}' "$_url")" || HTTP_CODE="000"
                ;;
            *)
                HTTP_CODE="$(curl -sSL --retry 3 --connect-timeout 15 \
                    -o "$_out" -w '%{http_code}' "$_url")" || HTTP_CODE="000"
                ;;
        esac
        [ -n "$HTTP_CODE" ] || HTTP_CODE="000"
    else
        if wget -q --tries=3 --timeout=15 -O "$_out" "$_url"; then
            HTTP_CODE="200"
        else
            HTTP_CODE="000"
        fi
    fi
    if [ "$HTTP_CODE" = "200" ]; then
        return 0
    fi
    rm -f "$_out"
    return 1
}

# ---------------------------------------------------------------------------
# Resolve download locations
# ---------------------------------------------------------------------------
if [ "$VERSION" = "latest" ]; then
    CF_BASE="${CF_RELEASES}/latest"
    GH_BASE="${GH_REPO}/releases/latest/download"
else
    CF_BASE="${CF_RELEASES}/${VERSION}"
    GH_BASE="${GH_REPO}/releases/download/v${VERSION#v}"
fi

ALLOW_FALLBACK=0
if [ -n "$BASE_URL_OPT" ]; then
    BASE_URL="$BASE_URL_OPT"
    SOURCE_LABEL="custom (--base-url)"
elif [ -n "${COBALT769_BASE_URL:-}" ]; then
    BASE_URL="$COBALT769_BASE_URL"
    SOURCE_LABEL="custom (COBALT769_BASE_URL)"
else
    case "$SOURCE" in
        github)
            BASE_URL="$GH_BASE"
            SOURCE_LABEL="GitHub Releases"
            ;;
        cloudflare)
            BASE_URL="$CF_BASE"
            SOURCE_LABEL="cobalt769.org"
            ;;
        auto)
            BASE_URL="$CF_BASE"
            SOURCE_LABEL="cobalt769.org"
            ALLOW_FALLBACK=1
            ;;
    esac
fi
BASE_URL="${BASE_URL%/}"

# ---------------------------------------------------------------------------
# Temp workspace
# ---------------------------------------------------------------------------
TMPDIR="$(mktemp -d 2>/dev/null || mktemp -d -t cobalt769)"
[ -n "$TMPDIR" ] && [ -d "$TMPDIR" ] || die "failed to create temporary directory"
trap 'rm -rf "$TMPDIR"' EXIT
# On signals: clean up and actually stop (a bare cleanup trap would resume execution).
trap 'rm -rf "$TMPDIR"; trap - EXIT; exit 130' INT
trap 'rm -rf "$TMPDIR"; trap - EXIT; exit 143' TERM

SUMS_PATH="$TMPDIR/$SUMS_FILE"
TARBALL_PATH="$TMPDIR/$TARBALL"
EXTRACT_DIR="$TMPDIR/extract"

info "Installing ${PROJECT} ${VERSION} for ${OS}/${ARCH} into ${PREFIX}"

# ---------------------------------------------------------------------------
# Fetch SHA256SUMS.txt (with Cloudflare -> GitHub fallback)
# ---------------------------------------------------------------------------
info "Fetching ${SUMS_FILE} from ${SOURCE_LABEL}: ${BASE_URL}/${SUMS_FILE}"
if ! http_get "${BASE_URL}/${SUMS_FILE}" "$SUMS_PATH"; then
    if [ "$ALLOW_FALLBACK" -eq 1 ]; then
        if [ "$HTTP_CODE" = "404" ]; then
            info "Not found on cobalt769.org (HTTP 404); falling back to GitHub Releases"
        else
            info "cobalt769.org unavailable (HTTP ${HTTP_CODE}); falling back to GitHub Releases"
        fi
        BASE_URL="$GH_BASE"
        SOURCE_LABEL="GitHub Releases"
        info "Fetching ${SUMS_FILE} from ${SOURCE_LABEL}: ${BASE_URL}/${SUMS_FILE}"
        http_get "${BASE_URL}/${SUMS_FILE}" "$SUMS_PATH" \
            || die "could not download ${SUMS_FILE} from GitHub Releases (HTTP ${HTTP_CODE}); check that version '${VERSION}' exists"
    else
        die "could not download ${BASE_URL}/${SUMS_FILE} (HTTP ${HTTP_CODE})"
    fi
fi

# Find expected checksum for our tarball (accepts "hash  name", "hash *name", "./name").
EXPECTED="$(awk -v f="$TARBALL" '
    { n = $2; sub(/^\*/, "", n); sub(/^\.\//, "", n) }
    n == f { print $1; exit }
' "$SUMS_PATH" | tr 'ABCDEF' 'abcdef')"

if [ -z "$EXPECTED" ]; then
    # Release exists but has no artifact for this platform.
    source_build_hint
fi

case "$EXPECTED" in
    *[!0-9a-f]*) die "malformed checksum entry for ${TARBALL} in ${SUMS_FILE}" ;;
esac
[ "${#EXPECTED}" -eq 64 ] || die "malformed checksum entry for ${TARBALL} in ${SUMS_FILE}"

# ---------------------------------------------------------------------------
# Fetch and verify tarball
# ---------------------------------------------------------------------------
info "Downloading ${BASE_URL}/${TARBALL}"
if ! http_get "${BASE_URL}/${TARBALL}" "$TARBALL_PATH"; then
    if [ "$HTTP_CODE" = "404" ]; then
        source_build_hint
    fi
    die "failed to download ${BASE_URL}/${TARBALL} (HTTP ${HTTP_CODE})"
fi

info "Verifying SHA-256 checksum"
ACTUAL="$(sha256_of "$TARBALL_PATH" | tr 'ABCDEF' 'abcdef')"
if [ "$ACTUAL" != "$EXPECTED" ]; then
    say "error: SHA-256 checksum mismatch for ${TARBALL}"
    say "  expected: ${EXPECTED}"
    say "  actual:   ${ACTUAL}"
    say "Refusing to install. The download may be corrupted or tampered with."
    exit 1
fi
info "Checksum OK (${ACTUAL})"

# ---------------------------------------------------------------------------
# Extract
# ---------------------------------------------------------------------------
mkdir "$EXTRACT_DIR"
gzip -dc "$TARBALL_PATH" | (cd "$EXTRACT_DIR" && tar -xf -) \
    || die "failed to extract ${TARBALL}"

# find_one RELATIVE_SUFFIX -> prints first regular file matching */SUFFIX
find_one() {
    _hit="$(find "$EXTRACT_DIR" -type f -path "*/$1" 2>/dev/null | head -n 1)"
    [ -n "$_hit" ] || die "release tarball is missing expected file: $1"
    printf '%s\n' "$_hit"
}

SRC_BIN="$(find_one "bin/${PROJECT}")"
SRC_SO="$(find_one "lib/${SO_NAME}")"
SRC_A="$(find_one "lib/libcobalt769_ffi.a")"
SRC_H="$(find_one "include/cobalt769.h")"
SRC_PY="$(find_one "python/cobalt769.py")"

# ---------------------------------------------------------------------------
# Install
# ---------------------------------------------------------------------------
DEST_BIN="${PREFIX}/bin/${PROJECT}"
DEST_SO="${PREFIX}/lib/${SO_NAME}"
DEST_A="${PREFIX}/lib/libcobalt769_ffi.a"
DEST_H="${PREFIX}/include/cobalt769.h"
DEST_PY_DIR="${PREFIX}/share/cobalt769/python"
DEST_PY="${DEST_PY_DIR}/cobalt769.py"

mkdir -p "${PREFIX}/bin" "${PREFIX}/lib" "${PREFIX}/include" "$DEST_PY_DIR" \
    || die "cannot create directories under ${PREFIX} (try a different --prefix or check permissions)"

# install_file SRC DEST MODE  (copy to temp name in target dir, then atomic rename)
install_file() {
    _tmp="${2}.tmp.$$"
    cp "$1" "$_tmp" || { rm -f "$_tmp"; die "failed to copy to $2"; }
    chmod "$3" "$_tmp" || { rm -f "$_tmp"; die "failed to chmod $2"; }
    mv -f "$_tmp" "$2" || { rm -f "$_tmp"; die "failed to install $2"; }
}

info "Installing files"
install_file "$SRC_BIN" "$DEST_BIN" 0755
install_file "$SRC_SO"  "$DEST_SO"  0755
install_file "$SRC_A"   "$DEST_A"   0644
install_file "$SRC_H"   "$DEST_H"   0644
install_file "$SRC_PY"  "$DEST_PY"  0644

# ---------------------------------------------------------------------------
# Summary
# ---------------------------------------------------------------------------
say ""
say "${PROJECT} ${VERSION} installed successfully (source: ${SOURCE_LABEL})"
say ""
say "Installed files:"
say "  ${DEST_BIN}"
say "  ${DEST_SO}"
say "  ${DEST_A}"
say "  ${DEST_H}"
say "  ${DEST_PY}"

case ":${PATH:-}:" in
    *":${PREFIX}/bin:"*|*":${PREFIX}/bin/:"*) ;;
    *)
        say ""
        say "NOTE: ${PREFIX}/bin is not in your PATH. Add it with:"
        say "  export PATH=\"${PREFIX}/bin:\$PATH\""
        say "(add that line to your shell profile, e.g. ~/.profile, ~/.bashrc or ~/.zshrc)"
        ;;
esac

say ""
say "To use the FFI library / Python bindings:"
if [ "$OS" = "darwin" ]; then
    say "  export DYLD_LIBRARY_PATH=\"${PREFIX}/lib:\${DYLD_LIBRARY_PATH:-}\""
else
    say "  export LD_LIBRARY_PATH=\"${PREFIX}/lib:\${LD_LIBRARY_PATH:-}\""
fi
say "  export PYTHONPATH=\"${DEST_PY_DIR}:\${PYTHONPATH:-}\""

say ""
say "Smoke test:"
say "  cobalt769 --version"
say "  (or: ${DEST_BIN} --version)"
