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

# Install script for SafelineAPI (systemd)
# Usage: sudo ./scripts/install.sh [install_dir]
# Default install_dir: /opt/safelineapi

PREFIX=${1:-/opt/safelineapi}
SERVICE_NAME=safelineapi
SYSTEMD_UNIT=/etc/systemd/system/${SERVICE_NAME}.service
ENV_FILE=/etc/default/${SERVICE_NAME}
USER_NAME=safeline

echo "Install SafelineAPI to ${PREFIX}"

if [ "$(id -u)" -ne 0 ]; then
  echo "This script must be run as root (or via sudo)" >&2
  exit 2
fi

mkdir -p "$PREFIX"

# Build binary if not present in repo
if [ ! -f "$PREFIX/safelineApi" ]; then
  echo "Building safelineApi..."
  # build from repo root (assumes script run from repo root)
  if [ -f ./cmd/safelineApi/main.go ]; then
    GOOS=${GOOS:-linux} GOARCH=${GOARCH:-amd64} go build -o "$PREFIX/safelineApi" ./cmd/safelineApi
  else
    echo "Cannot find source to build. Place binary at ${PREFIX}/safelineApi or run from repo root." >&2
  fi
fi

# Copy config.example.json to config.json if no config exists
if [ -f "$PREFIX/config.json" ]; then
  echo "Found existing config.json in ${PREFIX}, leaving in place."
else
  if [ -f ./config.example.json ]; then
    cp ./config.example.json "$PREFIX/config.json"
    echo "Copied example config to ${PREFIX}/config.json — edit and add secrets before starting service."
  else
    echo "No config.example.json found in repo root. Create ${PREFIX}/config.json before starting service." >&2
  fi
fi

# copy service unit
cp contrib/safelineapi.service "$SYSTEMD_UNIT"
chmod 644 "$SYSTEMD_UNIT"

# copy example env file if not exists
if [ -f /etc/default/${SERVICE_NAME} ]; then
  echo "/etc/default/${SERVICE_NAME} already exists — leaving in place."
else
  cp contrib/safelineapi.env "$ENV_FILE"
  chmod 644 "$ENV_FILE"
  echo "Wrote ${ENV_FILE}. Edit it to set CONFIG_PATH and optional runtime vars."
fi

# create system user if missing
if id -u "$USER_NAME" >/dev/null 2>&1; then
  echo "User $USER_NAME exists"
else
  useradd --system --no-create-home --shell /usr/sbin/nologin "$USER_NAME"
  echo "Created system user $USER_NAME"
fi

# chown files
chown -R ${USER_NAME}:${USER_NAME} "$PREFIX"

systemctl daemon-reload
systemctl enable --now ${SERVICE_NAME}.service

echo "Installation complete. Check status with: systemctl status ${SERVICE_NAME}.service"
