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

if [ "$(id -u)" -ne 0 ]; then
  echo "Please run as root: sudo ./install.sh"
  exit 1
fi

SRC_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

echo "Installing GAL-2 Time Contract RC2..."

id -u gal2 >/dev/null 2>&1 || useradd --system --home /opt/gal2 --shell /usr/sbin/nologin gal2

mkdir -p /opt/gal2
mkdir -p /opt/gal2/var/cache
mkdir -p /opt/gal2/var/usage
mkdir -p /etc/gal2

cp -R "$SRC_DIR/opt/gal2/"* /opt/gal2/
cp "$SRC_DIR/systemd/gal2-timecontract.service" /etc/systemd/system/gal2-timecontract.service

if [ ! -f /etc/gal2/daemon.env ]; then
  cp /opt/gal2/config/daemon.env.sample /etc/gal2/daemon.env
  echo "Created /etc/gal2/daemon.env from sample."
  echo "Edit /etc/gal2/daemon.env and set GAL2_API_KEY before starting."
fi

chown -R gal2:gal2 /opt/gal2
chmod 700 /etc/gal2
chmod 600 /etc/gal2/daemon.env || true
chmod 755 /opt/gal2/bin/gal2d.py
chmod 755 /opt/gal2/bin/gal2-daemon-linux.sh

systemctl daemon-reload
systemctl enable gal2-timecontract.service

echo "Install complete."
echo "Start with: sudo systemctl start gal2-timecontract.service"
echo "Check with: curl http://127.0.0.1:9095/contract"
