#!/usr/bin/env bash
# Install FastestInternetEver portable bundle on Linux (requires root).
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
# shellcheck source=../../scripts/names.sh
source "$(cd "$(dirname "$0")/../.." && pwd)/scripts/names.sh"
PREFIX="${PREFIX:-/usr/local}"
BIN_DIR="$PREFIX/bin"
ETC_DIR="/etc/fastestinternetever"
SYSTEMD_UNIT="fastestinternetever-dns.service"

if [[ "$(id -u)" -ne 0 ]]; then
  echo "Run as root: sudo $0" >&2
  exit 1
fi

mkdir -p "$BIN_DIR" "$ETC_DIR"
install -m 755 "$SCRIPT_DIR/$FIE_DNS_BIN" "$BIN_DIR/$FIE_DNS_BIN"
install -m 644 "$SCRIPT_DIR/$FIE_CONFIGFILE" "$ETC_DIR/$FIE_CONFIGFILE"

if [[ -f "$SCRIPT_DIR/$FIE_AGENT_BIN" ]]; then
  install -m 755 "$SCRIPT_DIR/$FIE_AGENT_BIN" "$BIN_DIR/$FIE_AGENT_BIN"
fi

if command -v systemctl >/dev/null 2>&1; then
  install -m 644 "$SCRIPT_DIR/$SYSTEMD_UNIT" "/etc/systemd/system/$SYSTEMD_UNIT"
  systemctl daemon-reload
  systemctl enable "$SYSTEMD_UNIT"
  systemctl restart "$SYSTEMD_UNIT"
  echo "FastestInternetEver DNS service enabled ($SYSTEMD_UNIT)"
else
  echo "systemctl not found; start manually:"
  echo "  $BIN_DIR/$FIE_DNS_BIN -conf $ETC_DIR/$FIE_CONFIGFILE"
fi

echo "FastestInternetEver DNS installed to $BIN_DIR/$FIE_DNS_BIN"
echo "Config: $ETC_DIR/$FIE_CONFIGFILE"