#!/usr/bin/env bash
# Maps syncservice.groovestats.com -> IP of syncplay.letalex.dev
# Usage: sudo ./enable-sync-redirect.sh
set -euo pipefail

ALIAS="${ALIAS:-syncservice.groovestats.com}"
TARGET="${TARGET:-syncplay.letalex.dev}"
MARKER="${MARKER:-# itgmania-custom-sync}"
HOSTS="${HOSTS:-/etc/hosts}"

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

IP="$(getent ahostsv4 "$TARGET" | awk 'NR==1 {print $1}')"
if [[ -z "$IP" ]]; then
  IP="$(dig +short A "$TARGET" | awk 'NR==1 {print; exit}')"
fi
if [[ -z "$IP" ]]; then
  echo "Failed to resolve $TARGET" >&2
  exit 1
fi

TMP="$(mktemp)"
trap 'rm -f "$TMP"' EXIT

grep -v -e "$ALIAS" -e "$MARKER" "$HOSTS" >"$TMP" || true
printf '%s  %s  %s\n' "$IP" "$ALIAS" "$MARKER" >>"$TMP"
cat "$TMP" >"$HOSTS"

if command -v resolvectl >/dev/null 2>&1; then
  resolvectl flush-caches >/dev/null 2>&1 || true
elif command -v systemd-resolve >/dev/null 2>&1; then
  systemd-resolve --flush-caches >/dev/null 2>&1 || true
fi

echo "Enabled: $ALIAS -> $IP ($TARGET)"
