#!/bin/sh
# moos installer: verify the signed release, unpack it under the user's
# data dir, link the launchers into PATH and (when GTK/WebKit is present)
# add a desktop entry. No root, no compiler, no state of yours removed.
#
#   curl -fsSLO https://moos.st/install.sh
#   sh install.sh
#   export PATH="$HOME/.local/bin:$PATH"
#   moos
#
# Read the script first if you like:  less install.sh   (q quits)
#
#   sh install.sh --uninstall      remove the app, keep identity/logs
#   sh install.sh --check          verify the release, install nothing
#   sh install.sh --version 0.1.3  pick a version (default below)
#   sh install.sh --no-desktop     skip the menu entry
#
# The artifact is checked twice: SHA-256 against SHA256SUMS, and that file
# against an RSA signature whose public key is embedded below. Both must
# pass before anything is unpacked. State (identity, wallet, tor, logs)
# lives outside the app dir and is never deleted by --uninstall.
set -eu

VERSION="${MOOS_VERSION:-0.1.3}"
BASE="${MOOS_BASE_URL:-https://moos.st/downloads}"
PREFIX="${MOOS_PREFIX:-$HOME/.local}"
DATA="${XDG_DATA_HOME:-$HOME/.local/share}/moos"
DESKTOP="${XDG_DATA_HOME:-$HOME/.local/share}/applications"
ICONS="${XDG_DATA_HOME:-$HOME/.local/share}/icons/hicolor/scalable/apps"
ALLOW_UNSIGNED=0
NO_DESKTOP=0
ACTION=install

say() { printf '%s\n' "$*"; }
die() { printf 'install: %s\n' "$*" >&2; exit 1; }

usage() {
    cat <<'EOF'
usage: sh install.sh [--version V] [--prefix DIR] [--no-desktop]
                     [--uninstall] [--check] [--allow-unsigned]

  --version V        release to install (default: 0.1.3)
  --prefix DIR       where to link the launchers (default: ~/.local)
  --no-desktop       do not write a .desktop entry
  --uninstall        remove the installed app; keep identity and logs
  --check            verify the signed release without installing
  --allow-unsigned   skip the signature check (checksum is still enforced)
EOF
}

while [ $# -gt 0 ]; do
    case "$1" in
        --version)   VERSION="${2:?--version needs a value}"; shift 2 ;;
        --prefix)    PREFIX="${2:?--prefix needs a value}"; shift 2 ;;
        --no-desktop) NO_DESKTOP=1; shift ;;
        --uninstall) ACTION=uninstall; shift ;;
        --check)     ACTION=check; shift ;;
        --allow-unsigned) ALLOW_UNSIGNED=1; shift ;;
        -h|--help)   usage; exit 0 ;;
        *)           die "unknown argument: $1 (try --help)" ;;
    esac
done

APP="$DATA/app/$VERSION"
BIN="$PREFIX/bin"
ASSET="moos-$VERSION-linux-x86_64.tar.gz"

case "$VERSION" in
    *[!0-9.]*|'') die "bad version: $VERSION" ;;
esac

# ---- uninstall ------------------------------------------------------------

if [ "$ACTION" = uninstall ]; then
    for f in "$BIN/moos" "$BIN/moos-tui"; do
        if [ -L "$f" ]; then
            rm -f "$f"
        fi
    done
    rm -f "$DESKTOP/moos.desktop" "$ICONS/moos.svg"
    if [ -d "$APP" ]; then
        rm -rf "$APP"
        say "removed $APP"
    else
        say "no app tree at $APP (nothing to remove)"
    fi
    rmdir "$DATA/app" 2>/dev/null || true
    if command -v update-desktop-database >/dev/null 2>&1; then
        update-desktop-database "$DESKTOP" >/dev/null 2>&1 || true
    fi
    say "kept your state: $DATA"
    say "  identity, wallet, tor and logs were not touched; delete $DATA by hand to erase them"
    exit 0
fi

# ---- preconditions --------------------------------------------------------

[ "$(id -u)" -ne 0 ] ||
    die "run this as your user, not root: a wallet install and its state belong to one user"
[ "$(uname -s)" = Linux ] || die "moos release artifacts are Linux-only (this is $(uname -s))"
[ "$(uname -m)" = x86_64 ] || die "this release is x86_64 only (this is $(uname -m))"
command -v curl >/dev/null 2>&1 || die "curl is required"
command -v tar >/dev/null 2>&1 || die "tar is required"
command -v sha256sum >/dev/null 2>&1 || die "sha256sum is required (coreutils)"

# The Rust binaries are built against glibc 2.34 (see docs/PACKAGING.md).
# Say so here rather than let the loader print a version error later.
if command -v getconf >/dev/null 2>&1; then
    glibc="$(getconf GNU_LIBC_VERSION 2>/dev/null | awk '{print $2}')"
    if [ -n "${glibc:-}" ] && ! awk -v have="$glibc" -v need="2.34" 'BEGIN {
            n=split(have,A,"."); m=split(need,B,".");
            for (i=1;i<=3;i++) {
                x=(i<=n?A[i]+0:0); y=(i<=m?B[i]+0:0);
                if (x>y) exit 0;
                if (x<y) exit 1;
            }
            exit 0;
        }'; then
        die "this release needs glibc 2.34 or newer (this system has $glibc)"
    fi
fi

tmp="$(mktemp -d)"
trap 'rm -rf "$tmp"' EXIT INT TERM

fetch() {  # url dest
    curl --proto '=https' --tlsv1.2 -fsSL "$1" -o "$2" ||
        die "download failed: $1"
}

# ---- verify ---------------------------------------------------------------

fetch "$BASE/SHA256SUMS" "$tmp/SHA256SUMS"

if [ "$ALLOW_UNSIGNED" = 0 ]; then
    command -v openssl >/dev/null 2>&1 ||
        die "openssl is required to verify the signature (or pass --allow-unsigned)"
    fetch "$BASE/SHA256SUMS.sig" "$tmp/SHA256SUMS.sig"
    cat > "$tmp/moos-release.pub.pem" <<'PUBKEY'
-----BEGIN PUBLIC KEY-----
MIIBojANBgkqhkiG9w0BAQEFAAOCAY8AMIIBigKCAYEAyDU1F7pB0erutFmbZhDq
taBTIXPkG1Jg31GGiZqrVN1g53VKxx9tq1udqERL1+gfSd+aoyFsRnGY+rQLy/TV
LRwp/eGtcL1bG6pbLy3wj+GsCDn9djBozotmvdFs5jAlc4YdX3FdSpEP95NxdsRk
6/UG016ahyph9NhQ5Ev7IHGLJsmbY2JLAnle2F5/+6VvSZosx0+VrcBO5Y0ZlV04
qG5hYcZnRgSyy2+muL2UYnez+/KhRiwffITozXXSrUTAWKUeFlxfEBtXJRWnqjZ8
pDTcjjR2lsihoLlmYyZDYk9CwwpFfEo5o/dwI+g5ihHGWISoAMETSpg0GBFM4BlT
SUj1JiE5pUydy2YfraEskazEU8WV6bgDP9VDRIbHx1vCnGrQLd/J3a9L+EMMt9aF
q4X8fzWTx9PwIlbJ6hNynOotDAD+/EflMZ11btEY3HUiI+jnEQtAWTiFSuXP7tyT
BAmp336DY76lHsEqrV54jB7Fsix47oB4P14oIXtngCr/AgMBAAE=
-----END PUBLIC KEY-----
PUBKEY
    openssl dgst -sha256 -verify "$tmp/moos-release.pub.pem" \
        -signature "$tmp/SHA256SUMS.sig" "$tmp/SHA256SUMS" >/dev/null 2>&1 ||
        die "signature verification FAILED: refusing to install"
    say "ok   signed release key"
else
    say "warn --allow-unsigned: signature check skipped"
fi

line="$(awk -v f="$ASSET" '$2==f {print; exit}' "$tmp/SHA256SUMS")"
[ -n "$line" ] || die "no checksum for $ASSET in SHA256SUMS"

fetch "$BASE/$ASSET" "$tmp/$ASSET"
( cd "$tmp" && printf '%s\n' "$line" | sha256sum -c - >/dev/null ) ||
    die "checksum FAILED for $ASSET"
say "ok   sha256 $ASSET"

if [ "$ACTION" = check ]; then
    say "release $VERSION verified; nothing installed"
    exit 0
fi

# ---- install --------------------------------------------------------------

tar xzf "$tmp/$ASSET" -C "$tmp"
src="$tmp/moos-$VERSION-linux-x86_64"
[ -x "$src/bin/moos-tui" ] && [ -x "$src/bin/moos-maker" ] ||
    die "release archive has no bin/moos-tui + bin/moos-maker"

mkdir -p "$DATA/app" "$BIN" "$DESKTOP" "$ICONS"
rm -rf "$APP"
mkdir -p "$APP"
cp -a "$src/." "$APP/"

ln -sfn "$APP/bin/moos-tui" "$BIN/moos-tui"
ln -sfn "$APP/bin/moos" "$BIN/moos"

# GTK 3 + WebKit2GTK 4.1 are host packages; the artifact only ships the
# webview helper. Without them the desktop shell cannot open a window.
gui=1
if ! command -v python3 >/dev/null 2>&1; then
    gui=0
else
    python3 - <<'PY' >/dev/null 2>&1 || gui=0
import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk  # noqa: F401
gi.require_version("WebKit2", "4.1")
from gi.repository import WebKit2  # noqa: F401
PY
fi

if [ "$gui" = 1 ] && [ "$NO_DESKTOP" = 0 ]; then
    cat > "$DESKTOP/moos.desktop" <<EOF
[Desktop Entry]
Type=Application
Name=moos
Comment=Monero <-> Ethereum atomic swaps
Exec="$BIN/moos"
Icon=moos
Terminal=false
Categories=Finance;Network;
StartupNotify=true
EOF
    cat > "$ICONS/moos.svg" <<'ICON'
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><rect x="2" y="2" width="60" height="60" fill="#0f0f0e" stroke="#8ee08e" stroke-width="4"/><text x="32" y="43" font-family="ui-monospace,Menlo,Consolas,monospace" font-size="34" font-weight="700" fill="#8ee08e" text-anchor="middle">m</text></svg>
ICON
    if command -v update-desktop-database >/dev/null 2>&1; then
        update-desktop-database "$DESKTOP" >/dev/null 2>&1 || true
    fi
fi

say ""
say "moos $VERSION installed to $APP"
say "  run        moos        desktop shell"
say "             moos-tui    terminal UI"
if [ "$gui" = 0 ]; then
    say "  note: GTK 3 / WebKit2GTK 4.1 not found, so no menu entry was written;"
    say "        moos still serves the UI at a local address; for the native window:"
    say "        install python3-gi gir1.2-gtk-3.0 gir1.2-webkit2-4.1"
fi
say "  state      $DATA (identity, wallet, tor, logs)"
say "  docs       https://moos.st/docs.html"
case ":$PATH:" in
    *":$BIN:"*) : ;;
    *) say "  PATH       add $BIN to PATH: export PATH=\"$BIN:\$PATH\"" ;;
esac
say "  uninstall  sh install.sh --uninstall"
