#!/usr/bin/env bash
set -euo pipefail

if [[ "${EUID}" -ne 0 ]]; then
  echo "Kjør som root: sudo bash $0"
  exit 1
fi

SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"

SRC_PS1="$REPO_ROOT/ps1/ps1.sh"
SRC_BANNER="$REPO_ROOT/banner/banner.sh"

DST_PS1="/etc/profile.d/ps1.sh"
DST_BANNER="/etc/profile.d/banner.sh"

BASH_BASHRC="/etc/bash.bashrc"

MARKER_START="# >>> dotfiles (managed) >>>"
MARKER_END="# <<< dotfiles (managed) <<<"

# Select install mode (PS1, banner, or both)
install_ps1=1
install_banner=1
season_mode="dynamic"
season_choice=""
style_choice="aurora"
style_pack="standard"
contest_layout="day-time-user"
holiday_choice="christmas"
git_choice="0"
if [[ -t 0 ]]; then
  echo "Install options:"
  echo "  1) PS1 only"
  echo "  2) Banner only"
  echo "  3) Both (PS1 + banner)"
  read -r -p "Choose [3]: " install_choice
  case "${install_choice}" in
    1) install_ps1=1; install_banner=0 ;;
    2) install_ps1=0; install_banner=1 ;;
    ""|3) install_ps1=1; install_banner=1 ;;
    *) echo "Invalid choice, using both."; install_ps1=1; install_banner=1 ;;
  esac

  if [[ "$install_ps1" -eq 1 ]]; then
    echo
  echo "PS1 mode:"
  echo "  1) Single season (static)"
  echo "  2) Dynamic season (changing)"
  echo "  3) Contest pack (static)"
  echo "  4) Holidays pack (static)"
  read -r -p "Choose [3]: " season_mode_choice
  case "${season_mode_choice}" in
    1)
        season_mode="static"
        echo "Pick a season:"
        echo "  1) Winter"
        echo "  2) Spring"
        echo "  3) Summer"
        echo "  4) Autumn"
        read -r -p "Choose [1]: " season_pick
        case "${season_pick}" in
          2) season_choice="spring" ;;
          3) season_choice="summer" ;;
          4) season_choice="autumn" ;;
          ""|1) season_choice="winter" ;;
          *) echo "Invalid choice, using winter."; season_choice="winter" ;;
        esac

        style_pack="standard"
        ;;
    2)
      season_mode="dynamic"
      style_pack="standard"
      ;;
    ""|3)
      season_mode="static"
      style_pack="contest"
      contest_layout="day-time-user"
        echo "Contest layout order:"
        echo "  1) day-time-user"
        echo "  2) user-time"
        echo "  3) time-user"
        echo "  4) day-time"
        read -r -p "Choose [1]: " layout_pick
        case "${layout_pick}" in
          2) contest_layout="user-time" ;;
          3) contest_layout="time-user" ;;
          4) contest_layout="day-time" ;;
          ""|1) contest_layout="day-time-user" ;;
          *) echo "Invalid choice, using day-time-user."; contest_layout="day-time-user" ;;
        esac
      ;;
    4)
      season_mode="dynamic"
      style_pack="holiday"
      echo "Holiday theme:"
      echo "  1) Christmas"
      echo "  2) Easter"
      echo "  3) Halloween"
      echo "  4) Valentine"
      echo "  5) Thanksgiving"
      echo "  6) New Year"
      read -r -p "Choose [1]: " holiday_pick
      case "${holiday_pick}" in
        2) holiday_choice="easter" ;;
        3) holiday_choice="halloween" ;;
        4) holiday_choice="valentine" ;;
        5) holiday_choice="thanksgiving" ;;
        6) holiday_choice="newyear" ;;
        ""|1) holiday_choice="christmas" ;;
        *) echo "Invalid choice, using christmas."; holiday_choice="christmas" ;;
      esac

      contest_layout="day-time-user"
      echo "Layout order:"
      echo "  1) day-time-user"
      echo "  2) user-time"
      echo "  3) time-user"
      echo "  4) day-time"
      read -r -p "Choose [1]: " layout_pick
      case "${layout_pick}" in
        2) contest_layout="user-time" ;;
        3) contest_layout="time-user" ;;
        4) contest_layout="day-time" ;;
        ""|1) contest_layout="day-time-user" ;;
        *) echo "Invalid choice, using day-time-user."; contest_layout="day-time-user" ;;
      esac
      ;;
    *)
      echo "Invalid choice, using dynamic."
      season_mode="dynamic"
      style_pack="standard"
        ;;
    esac

    if [[ "$style_pack" == "contest" ]]; then
      echo
      echo "Style presets:"
      echo "  1) Aurora  - Powerline blocks, seasonal palette, two-line"
      echo "     Preview: [date time user] > [@host /path]"
      echo "  2) Neon    - Magenta/cyan cyber blocks, high contrast"
      echo "     Preview: [user time] > [@host /path]"
      echo "  3) Forge   - Warm copper blocks, heavy frame"
      echo "     Preview: [date time user] > [@host /path]"
      echo "  4) Circuit - Green scanline, minimal rails"
      echo "     Preview: [user time] - @host /path"
      echo "  5) Mono    - Clean monochrome, fast read"
      echo "     Preview: [date time user] @host /path"
      echo "  6) Git     - Minimal with git capsule"
      echo "     Preview: [date time user] @host - /path (git)"
      echo "  7) Hawolex - Winter neon, tech icons"
      echo "     Preview: [date time user] @host - /path"
      read -r -p "Choose style [1]: " style_pick
      case "${style_pick}" in
        2) style_choice="neon" ;;
        3) style_choice="forge" ;;
        4) style_choice="circuit" ;;
        5) style_choice="mono" ;;
        6) style_choice="git" ;;
        7) style_choice="hawolex" ;;
        ""|1) style_choice="aurora" ;;
        *) echo "Invalid choice, using aurora."; style_choice="aurora" ;;
      esac

      if [[ "$style_choice" == "hawolex" ]]; then
        read -r -p "Enable git capsule? [y/N]: " git_pick
        case "${git_pick}" in
          y|Y) git_choice="1" ;;
          *) git_choice="0" ;;
        esac
      fi
    else
      style_choice="aurora"
    fi
  fi
fi

if [[ "$install_banner" -eq 1 ]]; then
  # Ensure required packages are installed (no prompt)
  missing_pkgs=()
  if ! command -v figlet >/dev/null 2>&1; then
    missing_pkgs+=("figlet")
  fi
  if ! command -v lolcat >/dev/null 2>&1 && [[ ! -x /usr/games/lolcat ]]; then
    missing_pkgs+=("lolcat")
  fi
  if ! command -v landscape-sysinfo >/dev/null 2>&1; then
    missing_pkgs+=("landscape-common")
  fi

  if ((${#missing_pkgs[@]} > 0)); then
    if command -v apt-get >/dev/null 2>&1; then
      apt-get update
      DEBIAN_FRONTEND=noninteractive apt-get install -y "${missing_pkgs[@]}"
    elif command -v dnf >/dev/null 2>&1; then
      dnf install -y "${missing_pkgs[@]}"
    elif command -v yum >/dev/null 2>&1; then
      yum install -y "${missing_pkgs[@]}"
    elif command -v pacman >/dev/null 2>&1; then
      pacman -Sy --noconfirm "${missing_pkgs[@]}"
    elif command -v zypper >/dev/null 2>&1; then
      zypper -n in "${missing_pkgs[@]}"
    else
      echo "Fant ingen støttet pakkehåndterer for å installere: ${missing_pkgs[*]}"
      exit 1
    fi
  fi

  # Prompt for punchline (stored globally)
  current_punchline="Hello"
  if [[ -r /etc/ps1-punchline ]]; then
    current_punchline="$(head -n 1 /etc/ps1-punchline 2>/dev/null || echo "Hello")"
    current_punchline="${current_punchline%%$'\r'}"
  fi

  if [[ -t 0 ]]; then
    echo "Punchline (enter for å beholde eksisterende):"
    read -r -p "> " new_punchline
  else
    new_punchline=""
  fi

  if [[ -n "${new_punchline}" ]]; then
    printf '%s\n' "${new_punchline}" > /etc/ps1-punchline
  else
    printf '%s\n' "${current_punchline}" > /etc/ps1-punchline
  fi
  chmod 0644 /etc/ps1-punchline
fi

# Copy modules
if [[ "$install_ps1" -eq 1 ]]; then
  cp -f "$SRC_PS1" "$DST_PS1"
  chmod 0644 "$DST_PS1"

  {
    printf 'PS1_SEASON_MODE=%s\n' "$season_mode"
    if [[ "$season_mode" == "static" && -n "$season_choice" ]]; then
      printf 'PS1_SEASON=%s\n' "$season_choice"
    fi
  } > /etc/ps1-season
  chmod 0644 /etc/ps1-season

  {
    printf 'PS1_STYLE=%s\n' "$style_choice"
    printf 'PS1_STYLE_PACK=%s\n' "$style_pack"
    if [[ "$style_pack" == "contest" || "$style_pack" == "holiday" ]]; then
      printf 'PS1_CONTEST_LAYOUT=%s\n' "$contest_layout"
    fi
    if [[ "$style_pack" == "holiday" ]]; then
      printf 'PS1_HOLIDAY=%s\n' "${holiday_choice:-christmas}"
    fi
    if [[ "$style_choice" == "hawolex" ]]; then
      printf 'PS1_GIT=%s\n' "$git_choice"
    fi
  } > /etc/ps1-style
  chmod 0644 /etc/ps1-style
else
  rm -f "$DST_PS1"
  rm -f /etc/ps1-season
  rm -f /etc/ps1-style
fi

if [[ "$install_banner" -eq 1 ]]; then
  cp -f "$SRC_BANNER" "$DST_BANNER"
  chmod 0644 "$DST_BANNER"
else
  rm -f "$DST_BANNER"
fi

# Ensure /etc/bash.bashrc sources both (idempotent)
tmp="$(mktemp)"
orig_mode="$(stat -c '%a' "$BASH_BASHRC")"
orig_owner="$(stat -c '%u' "$BASH_BASHRC")"
orig_group="$(stat -c '%g' "$BASH_BASHRC")"
awk -v s="$MARKER_START" -v e="$MARKER_END" '
  $0==s {inside=1; next}
  $0==e {inside=0; next}
  !inside {print}
' "$BASH_BASHRC" > "$tmp"

cat >> "$tmp" <<EOF

$MARKER_START
# Load PS1 + Banner (managed)
$(if [[ "$install_ps1" -eq 1 ]]; then cat <<'INNER'
if [ -r "/etc/profile.d/ps1.sh" ]; then
  . "/etc/profile.d/ps1.sh"
fi
INNER
fi)
$(if [[ "$install_banner" -eq 1 ]]; then cat <<'INNER'
if [ -r "/etc/profile.d/banner.sh" ]; then
  . "/etc/profile.d/banner.sh"
fi
INNER
fi)
$MARKER_END
EOF

install -m "$orig_mode" -o "$orig_owner" -g "$orig_group" "$tmp" "$BASH_BASHRC"
if command -v restorecon >/dev/null 2>&1; then
  restorecon "$BASH_BASHRC" >/dev/null 2>&1 || true
fi
rm -f "$tmp"

echo "✅ Installert globalt (Linux/WSL):"
if [[ "$install_ps1" -eq 1 ]]; then
  echo "  - $DST_PS1"
fi
if [[ "$install_banner" -eq 1 ]]; then
  echo "  - $DST_BANNER"
fi
echo "  - sourcet fra $BASH_BASHRC"
echo
echo "Åpne et nytt shell for å se endringene."
echo
echo "Disable per bruker:"
echo "  export DISABLE_GLOBAL_PS1=1"
echo "  export DISABLE_GLOBAL_BANNER=1"
echo "  eller:"
echo "  mkdir -p ~/.config/ps1 && touch ~/.config/ps1/disable  # disable PS1"
echo "  mkdir -p ~/.config/ps1 && touch ~/.config/ps1/disable-banner  # disable banner"
