#!/bin/bash
set -e

# ───── Configuration ─────
MARKER_DIR="/etc/setup-markers"
MARKER="$MARKER_DIR/locale_configured"
AREA="Europe"
ZONE="Brussels"
ZONEINFO_FILE="/usr/share/zoneinfo/${AREA}/${ZONE}"
LOCALES=("fr_BE.UTF-8" "en_US.UTF-8" "en_GB.UTF-8") 
DEFAULT_LOCALE="fr_BE.UTF-8"

# ───── Parse CLI Arguments ─────
FORCE=false
for arg in "$@"; do
  case "$arg" in
    --force)
      FORCE=true
      echo "⚠️  Force mode enabled — setup will re-run even if marker exists."
      ;;
    --help|-h)
      echo "Usage: $0 [--force]"
      echo "  --force   Re-run setup even if already marked as completed"
      exit 0
      ;;
    *)
      echo "❌ Unknown option: $arg"
      echo "Run with --help for usage."
      exit 1
      ;;
  esac
done

# ───── Check Marker ─────
sudo mkdir -p "$MARKER_DIR"
if sudo test -f "$MARKER" && [[ "$FORCE" != true ]]; then
  echo "✅ Locale & timezone already configured — skipping setup."
  echo "👉 Use --force to re-run setup."
  exit 0
fi

echo "🌍 Configuring locale & timezone..."

# ───── Timezone Configuration ─────
echo "🕒 Setting timezone to ${AREA}/${ZONE}"
sudo ln -sf "$ZONEINFO_FILE" /etc/localtime
sudo dpkg-reconfigure --frontend=noninteractive tzdata

# ───── Locale Configuration ─────
echo "🗣️ Enabling locales: ${LOCALES[*]}"
sudo cp /usr/share/i18n/SUPPORTED /etc/locale.gen

# Comment all lines first, then uncomment selected locales
sudo sed -i 's/^[^#]/#&/' /etc/locale.gen
for locale in "${LOCALES[@]}"; do
  sudo sed -i "s/^# *\(${locale}\s\+UTF-8\)/\1/" /etc/locale.gen
done

# Set default locale in debconf
echo "🌐 Setting default system locale to $DEFAULT_LOCALE"
echo "locales locales/default_environment_locale select $DEFAULT_LOCALE" | sudo debconf-set-selections

# Reconfigure
sudo rm -f /etc/default/locale
sudo dpkg-reconfigure --frontend=noninteractive locales

# ───── Update Environment ─────
echo "🔧 Updating locale environment variables..."
sudo update-locale \
  LANG="$DEFAULT_LOCALE" \
  LANGUAGE='fr_BE:fr:en_US:en' \
  LC_ALL="$DEFAULT_LOCALE" \
  LC_CTYPE="$DEFAULT_LOCALE" \
  LC_COLLATE="$DEFAULT_LOCALE" \
  LC_MESSAGES="$DEFAULT_LOCALE" \
  LC_NUMERIC="$DEFAULT_LOCALE" \
  LC_TIME="$DEFAULT_LOCALE" \
  LC_MONETARY="$DEFAULT_LOCALE" \
  LC_PAPER="$DEFAULT_LOCALE" \
  LC_NAME="$DEFAULT_LOCALE" \
  LC_ADDRESS="$DEFAULT_LOCALE" \
  LC_TELEPHONE="$DEFAULT_LOCALE" \
  LC_MEASUREMENT="$DEFAULT_LOCALE" \
  LC_IDENTIFICATION="$DEFAULT_LOCALE"

# ───── Check for orphaned locale references ─────
echo "🧹 Checking for invalid locale references..."

invalid_vars=()
for var in LANG LANGUAGE LC_ALL LC_CTYPE LC_COLLATE LC_MESSAGES LC_NUMERIC LC_TIME LC_MONETARY LC_PAPER LC_NAME LC_ADDRESS LC_TELEPHONE LC_MEASUREMENT LC_IDENTIFICATION; do
  val=$(printenv "$var")
  if [[ -n "$val" ]]; then
    normalized_val=$(echo "$val" | tr '[:upper:]' '[:lower:]' | sed 's/\.utf-8/.utf8/')
    if ! locale -a | tr '[:upper:]' '[:lower:]' | grep -Fxq "$normalized_val"; then
      echo "⚠️  $var is set to \"$val\" but this locale is not available on the system."
      invalid_vars+=("$var")
    fi
  fi
done

if [[ ${#invalid_vars[@]} -gt 0 ]]; then
  echo "🚫 Detected orphaned locale variables. Cleaning /etc/default/locale..."

  # Backup first
  sudo cp /etc/default/locale /etc/default/locale.bak

  for var in "${invalid_vars[@]}"; do
    sudo sed -i "/^$var=/d" /etc/default/locale
  done

  echo "✅ Cleaned invalid locale references. You may need to logout/login for changes to apply."
fi

# ───── Create Marker ─────
echo "📌 Writing marker to $MARKER"
sudo mkdir -p "$MARKER_DIR"
sudo touch "$MARKER"

echo "✅ Locale and timezone configuration complete."