#!/usr/bin/env bash
# Install FastestInternetEver portable bundle on macOS (requires sudo for /usr/local paths).
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="$PREFIX/etc/fastestinternetever"
LOG_DIR="$PREFIX/var/log/fastestinternetever"
PLIST_DST="/Library/LaunchDaemons/com.fastestinternetever.dns.plist"

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

mkdir -p "$BIN_DIR" "$ETC_DIR" "$LOG_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"
install -m 644 "$SCRIPT_DIR/com.fastestinternetever.dns.plist" "$PLIST_DST"

launchctl bootout system/com.fastestinternetever.dns 2>/dev/null || true
launchctl bootstrap system "$PLIST_DST"
launchctl enable system/com.fastestinternetever.dns
launchctl kickstart -k system/com.fastestinternetever.dns

HELPER_SRC="$SCRIPT_DIR/fie-privileged-helper"
SUDOERS_SRC="$SCRIPT_DIR/sudoers.fastestinternetever"
HELPER_DST="/usr/local/libexec/fastestinternetever/fie-privileged-helper"
SUDOERS_DST="/etc/sudoers.d/fastestinternetever"
if [[ -f "$HELPER_SRC" && -f "$SUDOERS_SRC" ]]; then
  mkdir -p "$(dirname "$HELPER_DST")"
  install -m 755 "$HELPER_SRC" "$HELPER_DST"
  install -m 440 "$SUDOERS_SRC" "$SUDOERS_DST"
  if command -v visudo >/dev/null 2>&1; then
    visudo -c -f "$SUDOERS_DST"
  fi
fi

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