#!/usr/bin/env bash
set -euo pipefail

SRC_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
GAL2_HOME="${GAL2_HOME:-/usr/local/gal2}"
GAL2_ETC="${GAL2_ETC:-/etc/gal2}"

if [[ "${EUID}" -ne 0 ]]; then
  echo "Please run as root: sudo ./scripts/install.sh"
  exit 1
fi

echo "GAL-2 Time Contract RC3.1 is a Limited Availability evaluator release."
echo "Use is subject to legal/EVALUATOR_TERMS.md, legal/DISCLAIMER.md, legal/CLAIM_BOUNDARY.md, and legal/SECURITY.md."
echo "This release is not certified for production critical infrastructure, safety-critical systems, regulated trading, medical systems, aviation, emergency services, or other high-risk environments without a separate written agreement."
echo

if [[ "${GAL2_ACCEPT_EVALUATOR_TERMS:-0}" != "1" ]]; then
  printf "Type ACCEPT to continue: "
  read -r GAL2_ACCEPT_INPUT
  if [[ "$GAL2_ACCEPT_INPUT" != "ACCEPT" ]]; then
    echo "Install cancelled."
    exit 1
  fi
fi

echo "Installing GAL-2 Time Contract for Linux..."
mkdir -p "$GAL2_HOME/bin" "$GAL2_HOME/var/cache" "$GAL2_HOME/var/usage" "$GAL2_HOME/logs" "$GAL2_ETC"

install -m 0755 "$SRC_DIR/src/gal2d.py" "$GAL2_HOME/bin/gal2d.py"
install -m 0755 "$SRC_DIR/src/gal2-doctor" "$GAL2_HOME/bin/gal2-doctor"
install -m 0755 "$SRC_DIR/src/gal2-daemon-linux.sh" "$GAL2_HOME/bin/gal2-daemon-linux.sh"

if [[ ! -f "$GAL2_ETC/daemon.env" ]]; then
  install -m 0600 "$SRC_DIR/packaging/daemon.env.sample" "$GAL2_ETC/daemon.env"
  echo "Created $GAL2_ETC/daemon.env from sample. Edit GAL2_API_KEY before production use."
else
  chmod 600 "$GAL2_ETC/daemon.env"
  echo "Preserved existing $GAL2_ETC/daemon.env"
fi

if command -v python3 >/dev/null 2>&1; then
  if python3 -m venv "$GAL2_HOME/venv" >/dev/null 2>&1; then
    "$GAL2_HOME/venv/bin/python3" -m pip install --upgrade pip >/dev/null
    "$GAL2_HOME/venv/bin/python3" -m pip install -r "$SRC_DIR/requirements.txt"
  else
    echo "python3 venv unavailable. Falling back to system python3."
  fi
else
  echo "python3 not found. Install python3 before starting GAL-2."
  exit 1
fi

if command -v systemctl >/dev/null 2>&1; then
  install -m 0644 "$SRC_DIR/systemd/gal2d.service" /etc/systemd/system/gal2d.service
  systemctl daemon-reload
  systemctl enable gal2d.service
  systemctl restart gal2d.service || true
  echo "systemd service installed: gal2d.service"
else
  echo "systemctl not available. Start manually with:"
  echo "  GAL2_ENV=$GAL2_ETC/daemon.env GAL2_HOME=$GAL2_HOME $GAL2_HOME/bin/gal2-daemon-linux.sh"
fi

echo "GAL-2 Linux install complete."
