#!/bin/sh
#
# PTL API installer for Linux x86_64.
#
#   curl -fsSL https://pkg.whsoft.ru/ptl_api/install.sh | sudo sh
#   sudo PTL_VERSION=3.0 ./install.sh
#
# Environment:
#   PTL_VERSION     version to install (default: latest.txt)
#   PTL_BASE_URL    release base (default: https://pkg.whsoft.ru/ptl_api)
#   PTL_PREFIX      install dir (default: /opt/ptl_api)
#   PTL_CONFIG_DIR  config dir (default: /etc/ptl_api)
#   PTL_USER        service user (default: ptl)
#   PTL_NO_START    set to 1 to install without starting the service
set -eu

BASE_URL=${PTL_BASE_URL:-https://pkg.whsoft.ru/ptl_api}
PREFIX=${PTL_PREFIX:-/opt/ptl_api}
CONFIG_DIR=${PTL_CONFIG_DIR:-/etc/ptl_api}
STATE_DIR=${PTL_STATE_DIR:-/var/lib/ptl_api}
USER_NAME=${PTL_USER:-ptl}
SERVICE=ptl-api
UNIT=/etc/systemd/system/${SERVICE}.service
RELEASE_PUB=RWTo6oG6xQCDUM/rT5zIvrxx+by0wEwvryIV48fGAFh8ibAdn9EKSCw3

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

[ "$(id -u)" -eq 0 ] || die "run as root (sudo)"
[ "$(uname -s)" = "Linux" ] || die "only Linux is supported"
case "$(uname -m)" in
	x86_64|amd64) ;;
	*) die "only x86_64 is supported (got $(uname -m))" ;;
esac
command -v curl >/dev/null || die "curl is required"
command -v sha256sum >/dev/null || die "sha256sum is required"
command -v useradd >/dev/null || die "useradd is required"

VER=${PTL_VERSION:-}
if [ -z "$VER" ]; then
	VER=$(curl -fsSL "$BASE_URL/latest.txt" | tr -d '[:space:]') || die "could not read $BASE_URL/latest.txt"
fi
[ -n "$VER" ] || die "could not determine the latest version"

BIN="ptl-api-${VER}-linux-amd64"
TMP=$(mktemp -d)
trap 'rm -rf "$TMP"' 0

log ">> PTL API $VER"
for f in "$BIN" SHA256SUMS SHA256SUMS.minisig config.example.json ptl-api.service QUICKSTART.md; do
	curl -fsSL "$BASE_URL/$VER/$f" -o "$TMP/$f" || die "download failed: $f"
done

( cd "$TMP" && sha256sum -c SHA256SUMS ) || die "checksum verification failed"
if command -v minisign >/dev/null 2>&1; then
	( cd "$TMP" && minisign -Vm SHA256SUMS -P "$RELEASE_PUB" ) || die "signature verification failed"
else
	log "   minisign not installed: checksum verified, signature skipped"
fi

log ">> user and directories"
if ! id "$USER_NAME" >/dev/null 2>&1; then
	useradd --system --home-dir "$PREFIX" --shell /usr/sbin/nologin "$USER_NAME"
fi
install -d -o "$USER_NAME" -g "$USER_NAME" -m 0750 "$PREFIX"
install -d -o root -g "$USER_NAME" -m 0750 "$CONFIG_DIR"
install -d -o "$USER_NAME" -g "$USER_NAME" -m 0750 "$STATE_DIR"

if command -v systemctl >/dev/null 2>&1; then
	log ">> stopping existing service (if any)"
	systemctl stop "$SERVICE" 2>/dev/null || true
fi

log ">> installing binary"
install -m 0755 -o root -g root "$TMP/$BIN" "$PREFIX/ptl-api"

if [ ! -f "$CONFIG_DIR/config.json" ]; then
	install -m 0640 -o root -g "$USER_NAME" "$TMP/config.example.json" "$CONFIG_DIR/config.json"
	log "   created $CONFIG_DIR/config.json (edit redis_url and controllers)"
else
	log "   keeping existing $CONFIG_DIR/config.json"
fi

if command -v systemctl >/dev/null 2>&1; then
	install -m 0644 -o root -g root "$TMP/ptl-api.service" "$UNIT"
	sed -i \
		-e "s|/opt/ptl_api|$PREFIX|g" \
		-e "s|/etc/ptl_api|$CONFIG_DIR|g" \
		-e "s|/var/lib/ptl_api|$STATE_DIR|g" \
		"$UNIT"
	systemctl daemon-reload 2>/dev/null || true
	if [ "${PTL_NO_START:-0}" = "1" ]; then
		log ">> service installed but not started (PTL_NO_START=1)"
	else
		if ! systemctl enable --now "$SERVICE"; then
			log "!! could not start $SERVICE automatically"
			log "   run: systemctl enable --now $SERVICE"
		fi
	fi
else
	log "!! systemctl not found: binary installed at $PREFIX/ptl-api"
fi

if command -v redis-cli >/dev/null 2>&1; then
	if redis-cli -h 127.0.0.1 -p 6379 ping 2>/dev/null | grep -q PONG; then
		log ">> Redis: OK (127.0.0.1:6379)"
	else
		log "!! Redis is not responding on 127.0.0.1:6379"
		log "   install/start Redis or change redis_url in $CONFIG_DIR/config.json"
	fi
else
	log "!! redis-cli not found — make sure Redis is available and redis_url is correct"
fi

log ""
log "PTL API $VER installed."
log "  config:  $CONFIG_DIR/config.json"
log "  binary:  $PREFIX/ptl-api"
log "  state:   $STATE_DIR/telemetry.json"
log "  service: systemctl status $SERVICE"
log "  check:   curl http://127.0.0.1:8000/_ping"
