#!/usr/bin/env bash
# Sync live DMS config into modules/hosts/<host>/_private/dms-defaults/ (see defaultSeedDir).
set -euo pipefail

usage() {
  cat <<EOF
Usage: $(basename "$0") [options] [host]

Copy ~/.config/DankMaterialShell/{settings,plugin_settings}.json into the
host seed directory (pretty-printed). Host defaults to this machine's hostname.

Options:
  --settings-only   Skip plugin_settings.json
  -n, --dry-run     Preview without writing
  -h, --help

Examples:
  just sync-dms
  $(basename "$0") --dry-run ideapad
EOF
}

find_repo_root() {
  local dir="${1:-$PWD}"
  while [[ "$dir" != "/" ]]; do
    if [[ -f "$dir/flake.nix" && -d "$dir/modules/hosts" ]]; then
      printf '%s\n' "$dir"
      return 0
    fi
    dir="$(dirname "$dir")"
  done
  return 1
}

resolve_host_module() {
  local hn="$1" repo_root="$2"
  local hosts_dir="${repo_root}/modules/hosts" dir name

  if [[ -d "${hosts_dir}/${hn}/_private" ]]; then
    printf '%s' "$hn"
    return 0
  fi

  for dir in "${hosts_dir}"/*/; do
    name="$(basename "$dir")"
    [[ -f "${dir}configuration.nix" ]] \
      && grep -qF "hostName = \"${hn}\";" "${dir}configuration.nix" \
      && { printf '%s' "$name"; return 0; }
  done

  echo "error: no host module for hostname '${hn}' (pass module name explicitly)" >&2
  return 1
}

sync_json() {
  local source="$1" dest="$2" label="$3"

  [[ -f "$source" ]] || { echo "skip: $label not found" >&2; return 0; }

  jq empty "$source"
  if [[ "$DRY_RUN" -eq 1 ]]; then
    echo "  $source -> $dest"
    return 0
  fi

  local tmp
  tmp="$(mktemp)"
  jq . "$source" >"$tmp"
  mv "$tmp" "$dest"
  echo "Updated $dest"
  UPDATED+=("$dest")
}

DRY_RUN=0
SETTINGS_ONLY=0
HOST=""
UPDATED=()

while [[ $# -gt 0 ]]; do
  case "$1" in
    -n | --dry-run) DRY_RUN=1; shift ;;
    --settings-only) SETTINGS_ONLY=1; shift ;;
    -h | --help) usage; exit 0 ;;
    -*) echo "error: unknown option: $1" >&2; usage >&2; exit 1 ;;
    *) HOST="$1"; shift ;;
  esac
done

REPO_ROOT="${CHIASSON_NIX_ROOT:-$(find_repo_root "$PWD" || true)}"
[[ -n "$REPO_ROOT" ]] || { echo "error: run from chiasson-nix repo root" >&2; exit 1; }
command -v jq >/dev/null || { echo "error: jq required" >&2; exit 1; }

if [[ -z "$HOST" ]]; then
  SYSTEM_HOSTNAME="$(hostname -s 2>/dev/null || hostname)"
  HOST="$(resolve_host_module "$SYSTEM_HOSTNAME" "$REPO_ROOT")"
  [[ "$HOST" == "$SYSTEM_HOSTNAME" ]] \
    && echo "Using host module: $HOST" \
    || echo "Using host module: $HOST (hostname: $SYSTEM_HOSTNAME)"
fi

HOST_PRIVATE="${REPO_ROOT}/modules/hosts/${HOST}/_private"
SEED_DIR="${HOST_PRIVATE}/dms-defaults"
DMS_CONFIG="${XDG_CONFIG_HOME:-$HOME/.config}/DankMaterialShell"

[[ -d "$HOST_PRIVATE" ]] || { echo "error: missing $HOST_PRIVATE" >&2; exit 1; }
[[ -f "${DMS_CONFIG}/settings.json" ]] || {
  echo "error: missing ${DMS_CONFIG}/settings.json" >&2
  exit 1
}

[[ "$DRY_RUN" -eq 1 ]] && echo "Would sync into $SEED_DIR:"
[[ "$DRY_RUN" -eq 0 ]] && mkdir -p "$SEED_DIR"

sync_json "${DMS_CONFIG}/settings.json" "${SEED_DIR}/settings.json" settings.json
[[ "$SETTINGS_ONLY" -eq 0 ]] \
  && sync_json "${DMS_CONFIG}/plugin_settings.json" "${SEED_DIR}/plugin_settings.json" plugin_settings.json

[[ "$DRY_RUN" -eq 1 || ${#UPDATED[@]} -eq 0 ]] && exit 0
git -C "$REPO_ROOT" diff --stat -- "${UPDATED[@]}" 2>/dev/null || true
