#!/usr/bin/env bash
# Installs (or updates) the 4lpha server on a fresh Ubuntu or Debian VPS.
#
#   curl -fsSL https://4lpha.si/install.sh | bash
#   curl -fsSL https://4lpha.si/install.sh | bash -s -- --setup-code K7QM-4XPA
#
# Options:
#   --setup-code CODE  the code that claims this server (the website's guide makes one for you)
#   --domain NAME      your own domain pointed at this server (default: <ip>.sslip.io)
#   --email ADDR       for Let's Encrypt notices about the certificate (optional)
#   --binary FILE      install this 4lpha-server file instead of downloading (testing only)
#
# Running it again updates 4lpha and keeps the settings, bots, keys and sign-in.
set -euo pipefail

# The 4lpha release key (Ed25519, hex). Every download is checked against it before it runs.
RELEASE_KEY="11683152dfa659240b8bac574f559bc1ca9be51105b921543d6a32582f4a7cfa"
DL="https://dl.4lpha.si"
SITE="https://4lpha.si"
APP=/opt/4lpha
DATA=/var/lib/4lpha
ETC=/etc/4lpha
USER_NAME=fourlpha

say() { printf '\033[1m%s\033[0m\n' "$*"; }
fail() { printf '\033[31m%s\033[0m\n' "$*" >&2; exit 1; }

setup_code="" domain="" email="" binary=""
while [ $# -gt 0 ]; do
  case "$1" in
    --setup-code) setup_code=$(printf %s "${2:-}" | tr a-z A-Z); shift 2 ;;
    --domain) domain="${2:-}"; shift 2 ;;
    --email) email="${2:-}"; shift 2 ;;
    --binary) binary="${2:-}"; shift 2 ;;
    *) fail "Unknown option $1. See the top of this script for the options." ;;
  esac
done

[ "$(id -u)" -eq 0 ] || fail "Run this as root: put sudo in front, or sign in as root."
command -v systemctl >/dev/null || fail "This needs a Linux with systemd, such as Ubuntu 24.04."
case "$(uname -m)" in
  x86_64|amd64) key=server ;;
  *) fail "4lpha's server runs on x86-64 (Intel or AMD) machines. Pick a regular x86 plan." ;;
esac
if [ -n "$setup_code" ] && [ "$(printf '%s' "$setup_code" | tr -cd 'A-Za-z0-9' | wc -c)" -lt 8 ]; then
  fail "The setup code needs at least 8 letters or digits."
fi

need=()
for c in curl openssl; do command -v "$c" >/dev/null || need+=("$c"); done
if [ ${#need[@]} -gt 0 ]; then
  say "Installing ${need[*]}"
  apt-get update -qq && DEBIAN_FRONTEND=noninteractive apt-get install -y -qq "${need[@]}" >/dev/null
fi

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

# --- The program ---------------------------------------------------------------------------
if [ -n "$binary" ]; then
  say "Using $binary (not downloaded, so not checked against the release key)"
  cp "$binary" "$tmp/4lpha-server"
else
  [ -n "$RELEASE_KEY" ] || fail "This copy of the installer has no release key yet. Get it from $SITE/install.sh"
  latest=$(curl -fsSL "$DL/latest.json") || fail "Couldn't reach $DL. Check the server's internet connection."
  name=$(printf '%s' "$latest" | tr -d ' \n' | sed -n "s/.*\"$key\":\"\([^\"]*\)\".*/\1/p")
  version=$(printf '%s' "$latest" | tr -d ' \n' | sed -n 's/.*"version":"\([^"]*\)".*/\1/p')
  [ -n "$name" ] || fail "There's no 4lpha server download yet. Try again later."
  case "$name" in 4lpha*) ;; *) fail "Unexpected download name $name" ;; esac
  say "Downloading 4lpha $version"
  curl -fSL --progress-bar "$SITE/dl/$name?from=install" -o "$tmp/4lpha-server"
  curl -fsSL "$DL/$name.sig" -o "$tmp/4lpha-server.sig"
  # An Ed25519 public key in the PEM form openssl reads: a fixed 12-byte header, then the key.
  {
    echo "-----BEGIN PUBLIC KEY-----"
    printf '%b' "$(printf '302a300506032b6570032100%s' "$RELEASE_KEY" | sed 's/../\\x&/g')" | base64 -w0
    echo
    echo "-----END PUBLIC KEY-----"
  } > "$tmp/release.pem"
  openssl pkeyutl -verify -pubin -inkey "$tmp/release.pem" -rawin -in "$tmp/4lpha-server" -sigfile "$tmp/4lpha-server.sig" >/dev/null 2>&1 \
    || fail "The download isn't signed by 4lpha, so it wasn't installed."
  say "Signature checked"
fi
chmod 755 "$tmp/4lpha-server"
"$tmp/4lpha-server" --version >/dev/null 2>&1 || fail "The 4lpha server program won't start on this machine."

# --- The machine ---------------------------------------------------------------------------
if ! id "$USER_NAME" >/dev/null 2>&1; then
  useradd --system --home-dir "$DATA" --shell /usr/sbin/nologin "$USER_NAME"
fi
install -d -m 755 -o "$USER_NAME" -g "$USER_NAME" "$APP"
install -d -m 700 -o "$USER_NAME" -g "$USER_NAME" "$DATA" "$DATA/config"
install -d -m 700 "$ETC"

# Signing orders needs the right time; Hyperliquid rejects ones with a stale timestamp.
timedatectl set-ntp true 2>/dev/null || true

# A small machine runs out of memory less easily with some swap.
if [ -z "$(swapon --show 2>/dev/null)" ] && [ ! -e /swapfile ] && [ "$(awk '/MemTotal/ {print $2}' /proc/meminfo)" -lt 4000000 ]; then
  say "Adding 1 GB of swap"
  if fallocate -l 1G /swapfile 2>/dev/null && chmod 600 /swapfile && mkswap /swapfile >/dev/null && swapon /swapfile; then
    echo '/swapfile none swap sw 0 0' >> /etc/fstab
  else
    rm -f /swapfile
  fi
fi

# Keep the system's own security updates coming.
if command -v apt-get >/dev/null; then
  dpkg -s unattended-upgrades >/dev/null 2>&1 || DEBIAN_FRONTEND=noninteractive apt-get install -y -qq unattended-upgrades >/dev/null 2>&1 || true
  printf 'APT::Periodic::Update-Package-Lists "1";\nAPT::Periodic::Unattended-Upgrade "1";\n' > /etc/apt/apt.conf.d/20auto-upgrades
fi

# Logs stay small.
install -d /etc/systemd/journald.conf.d
printf '[Journal]\nSystemMaxUse=200M\n' > /etc/systemd/journald.conf.d/4lpha.conf
systemctl restart systemd-journald 2>/dev/null || true

# --- Address -------------------------------------------------------------------------------
if [ -z "$domain" ] && [ -s "$ETC/domain" ]; then domain=$(cat "$ETC/domain"); fi
if [ -z "$email" ] && [ -s "$ETC/email" ]; then email=$(cat "$ETC/email"); fi
if [ -z "$domain" ]; then
  ip=$(ip -4 route get 1.1.1.1 2>/dev/null | awk '{for (i = 1; i < NF; i++) if ($i == "src") print $(i + 1)}')
  case "$ip" in 10.*|192.168.*|172.1[6-9].*|172.2[0-9].*|172.3[01].*|100.*|"") ip=$(curl -fsS4 https://api.ipify.org || true) ;; esac
  [ -n "$ip" ] || fail "Couldn't find this server's public address. Run again with --domain."
  # sslip.io answers <ip with dashes>.sslip.io with that IP, so the server gets a name, and a
  # proper HTTPS certificate, without buying a domain.
  domain="${ip//./-}.sslip.io"
fi
printf '%s\n' "$domain" > "$ETC/domain"
if [ -n "$email" ]; then printf '%s\n' "$email" > "$ETC/email"; fi

# --- The key that seals stored keys --------------------------------------------------------
# Kept by systemd, encrypted with this machine's own key, so a copy of /var/lib/4lpha alone
# doesn't unlock anything. A server set up before this kept it in config/master.key; that stays.
cred=""
if [ -s "$ETC/master-key.cred" ]; then
  cred="LoadCredentialEncrypted=master-key:$ETC/master-key.cred"
elif [ ! -e "$DATA/config/master.key" ] && command -v systemd-creds >/dev/null; then
  if openssl rand -hex 32 | systemd-creds encrypt --name=master-key - "$ETC/master-key.cred" 2>/dev/null; then
    chmod 600 "$ETC/master-key.cred"
    cred="LoadCredentialEncrypted=master-key:$ETC/master-key.cred"
  else
    rm -f "$ETC/master-key.cred"
  fi
fi

# --- The service ---------------------------------------------------------------------------
# Runs before each start: when an update keeps failing to start, put the old version back.
cat > "$APP/rollback-check" <<'EOF'
#!/bin/sh
cd /opt/4lpha || exit 0
[ -e .update-pending ] || exit 0
tries=$(( $(cat .update-tries 2>/dev/null || echo 0) + 1 ))
echo "$tries" > .update-tries
if [ "$tries" -gt 3 ] && [ -e 4lpha-server.old ]; then
  echo "The new version failed to start 3 times; going back to the previous one"
  mv -f 4lpha-server.old 4lpha-server
  rm -f .update-pending .update-tries
fi
exit 0
EOF
chmod 755 "$APP/rollback-check"
chown "$USER_NAME:$USER_NAME" "$APP/rollback-check"

args="--data $DATA --domain $domain"
if [ -n "$email" ]; then args="$args --email $email"; fi
cat > /etc/systemd/system/4lpha.service <<EOF
[Unit]
Description=4lpha server
After=network-online.target
Wants=network-online.target
StartLimitIntervalSec=0

[Service]
User=$USER_NAME
Group=$USER_NAME
ExecStartPre=$APP/rollback-check
ExecStart=$APP/4lpha-server $args
$cred
Restart=always
RestartSec=3
TimeoutStopSec=30
LimitNOFILE=65536
UMask=0077
# Port 443 without running as root, and nothing else.
AmbientCapabilities=CAP_NET_BIND_SERVICE
CapabilityBoundingSet=CAP_NET_BIND_SERVICE
NoNewPrivileges=yes
ProtectSystem=strict
ReadWritePaths=$DATA $APP
ProtectHome=yes
PrivateTmp=yes
PrivateDevices=yes
ProtectKernelTunables=yes
ProtectKernelModules=yes
ProtectKernelLogs=yes
ProtectControlGroups=yes
ProtectClock=yes
ProtectHostname=yes
RestrictNamespaces=yes
RestrictRealtime=yes
RestrictSUIDSGID=yes
LockPersonality=yes
RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX
SystemCallArchitectures=native

[Install]
WantedBy=multi-user.target
EOF

# A command for the owner: 4lpha setup-code, reset-login, status, logs, restart, update.
cat > /usr/local/bin/4lpha <<EOF
#!/bin/sh
run() { runuser -u $USER_NAME -- $APP/4lpha-server "\$@" --data $DATA; }
[ "\$(id -u)" -eq 0 ] || { echo "Run it as root: sudo 4lpha \$*"; exit 1; }
case "\$1" in
  address) echo "https://\$(cat $ETC/domain)" ;;
  setup-code) run setup-code ;;
  reset-login) systemctl stop 4lpha; run reset-login; systemctl start 4lpha ;;
  status) systemctl status 4lpha --no-pager ;;
  logs) journalctl -u 4lpha -n 200 -f ;;
  restart) systemctl restart 4lpha ;;
  update) curl -fsSL $SITE/install.sh | bash ;;
  *) echo "4lpha address | setup-code | reset-login | status | logs | restart | update" ;;
esac
EOF
chmod 755 /usr/local/bin/4lpha

# Shown when you sign in to the server over SSH.
if [ -d /etc/update-motd.d ]; then
  cat > /etc/update-motd.d/99-4lpha <<EOF
#!/bin/sh
echo
echo "  4lpha is at https://\$(cat $ETC/domain)"
[ -e $DATA/config/setup-code.txt ] && echo "  Setup code: \$(cat $DATA/config/setup-code.txt)"
echo "  Commands: 4lpha status | logs | setup-code | reset-login | update"
echo
EOF
  chmod 755 /etc/update-motd.d/99-4lpha
fi

# Firewall: SSH and HTTPS only.
if command -v ufw >/dev/null; then
  ufw allow OpenSSH >/dev/null 2>&1 || ufw allow 22/tcp >/dev/null
  ufw allow 443/tcp >/dev/null
  ufw --force enable >/dev/null
fi

# The owner's own setup code, before the server first starts (it keeps one it finds).
if [ -n "$setup_code" ] && [ ! -e "$DATA/config/auth.json" ]; then
  printf '%s\n' "$setup_code" > "$DATA/config/setup-code.txt"
fi
chown -R "$USER_NAME:$USER_NAME" "$DATA"
chmod 600 "$DATA/config/setup-code.txt" 2>/dev/null || true

# --- Put it in place and start -------------------------------------------------------------
updating=false
[ -e "$APP/4lpha-server" ] && updating=true
systemctl daemon-reload
systemctl stop 4lpha 2>/dev/null || true
install -m 755 -o "$USER_NAME" -g "$USER_NAME" "$tmp/4lpha-server" "$APP/4lpha-server"
rm -f "$APP/.update-pending" "$APP/.update-tries"
systemctl enable --now 4lpha >/dev/null 2>&1

for _ in $(seq 1 30); do
  systemctl is-active --quiet 4lpha && { [ -e "$DATA/config/setup-code.txt" ] || [ -e "$DATA/config/auth.json" ]; } && break
  sleep 1
done
systemctl is-active --quiet 4lpha || fail "4lpha didn't start. See what went wrong with: 4lpha logs"

echo
if $updating; then say "4lpha is updated to $("$APP/4lpha-server" --version)."; else say "4lpha is installed."; fi
echo
echo "  Open:        https://$domain"
if [ ! -e "$DATA/config/auth.json" ] && [ -e "$DATA/config/setup-code.txt" ]; then
  echo "  Setup code:  $(cat "$DATA/config/setup-code.txt")"
fi
echo
echo "  The first visit can take up to a minute while the server gets its HTTPS certificate."
echo "  Your bots run here around the clock; close the browser whenever you like."
echo
