#!/usr/bin/env bash
# Install the Vapor media server on a systemd Linux box:
#   /opt/vapor/vapord           the server binary (owned by the service user,
#                               because the daily self-update swaps it in place)
#   /var/lib/vapor/             library database, staged updates, plugins
#   /etc/vapor/vapor.env        optional environment overrides
#   /etc/systemd/system/vapor.service
#
# Run from the unpacked release directory (vapord + vapor.service beside it):
#   sudo ./install.sh
#
# Env parameters:
#   VAPOR_USER   service account (default: vapor, created as a system user
#                if missing; set to an existing user to run as them)
set -euo pipefail

if [ "$(id -u)" -ne 0 ]; then
  echo "install.sh must run as root (sudo ./install.sh)" >&2
  exit 1
fi
cd "$(dirname "$0")"
if [ ! -f vapord ]; then
  echo "vapord not found beside install.sh; run from the unpacked release" >&2
  exit 1
fi

VAPOR_USER="${VAPOR_USER:-vapor}"
if ! id -u "$VAPOR_USER" >/dev/null 2>&1; then
  echo ">> creating system user $VAPOR_USER"
  useradd --system --home-dir /var/lib/vapor --shell /usr/sbin/nologin "$VAPOR_USER"
fi

echo ">> installing /opt/vapor/vapord"
mkdir -p /opt/vapor
# Stop first so the copy never races a running binary (fresh installs have
# no unit yet; ignore).
systemctl stop vapor 2>/dev/null || true
install -m 0755 vapord /opt/vapor/vapord.new
chown "$VAPOR_USER" /opt/vapor/vapord.new
mv -f /opt/vapor/vapord.new /opt/vapor/vapord
# The service user owns /opt/vapor so the daily self-update can create a
# durable backup and atomically replace the binary in place.
chown -R "$VAPOR_USER" /opt/vapor
chmod 0755 /opt/vapor /opt/vapor/vapord

echo ">> data dir /var/lib/vapor"
mkdir -p /var/lib/vapor
chown -R "$VAPOR_USER" /var/lib/vapor

echo ">> config /etc/vapor/vapor.env"
mkdir -p /etc/vapor
if [ ! -f /etc/vapor/vapor.env ]; then
  cat > /etc/vapor/vapor.env <<'EOF'
# Vapor environment overrides (one KEY=value per line). Examples:
# MEDIASERVER_ADDR=0.0.0.0:8770        # expose on the LAN (clients must pair)
# MEDIASERVER_NO_SELFUPDATE=1          # opt out of the daily update check
# MEDIASERVER_UPDATE_MANIFEST=…        # point at a different release channel
EOF
fi

echo ">> systemd unit vapor.service (User=$VAPOR_USER)"
sed "s/^User=.*/User=$VAPOR_USER/" vapor.service > /etc/systemd/system/vapor.service
systemctl daemon-reload
systemctl enable --now vapor

echo
echo "Vapor is running: http://127.0.0.1:8770 (loopback only by default)"
echo "  status:  systemctl status vapor"
echo "  logs:    journalctl -u vapor -f"
echo "  expose:  set MEDIASERVER_ADDR in /etc/vapor/vapor.env, then systemctl restart vapor"
echo "  updates: checked daily; applied automatically on the next restart/reboot"
