#!/bin/bash

# omarchy:summary=Set this machine's edition: China or global (docs/regions.md)
# omarchy:args=<cn|global>
# omarchy:examples=omarchy region set cn | omarchy region set global
# omarchy:requires-sudo=true

set -euo pipefail

# Exit on a signal even while a child survives it, so the switch never runs on.
trap 'exit 129' HUP
trap 'exit 130' INT
trap 'exit 143' TERM

if (( $# != 1 )) || [[ $1 != "cn" && $1 != "global" ]]; then
  echo "Usage: omarchy-region-set <cn|global>" >&2
  exit 1
fi
region=$1
environment="$OMARCHY_PATH/default/regions/$region/environment.conf"

# sudo remembers a password per terminal and script(1) opens a new one, so
# start the update's log here, as omarchy-channel-set does: the update this
# hands off to then asks no second time.
if [[ -z ${OMARCHY_UPDATE_LOGGED:-} ]]; then
  if [[ ${SHELL@a} == *x* ]]; then
    printf -v script_command 'export SHELL=%q; ' "$SHELL"
  else
    script_command='unset SHELL; '
  fi
  script_command+="$(printf '%q ' "$0" "$@"); exit \$?"
  exec env OMARCHY_UPDATE_LOGGED=1 SHELL=/usr/bin/bash script -qefc "$script_command" "/tmp/omarchy-update.log"
fi

# A failure past this point leaves the switch half-applied, so say how to
# pick it back up rather than dying silently under set -e.
trap 'echo -e "\nThe edition switch did not complete. Review the error above, then rerun: omarchy-region-set '"$region"'" >&2' ERR

printf '%s\n' "$region" | sudo install -D -m 644 /dev/stdin /etc/omarchy/region

# The region's developer-tool mirrors, from the next restart.
if [[ -f $environment ]]; then
  sudo install -D -m 644 "$environment" /etc/environment.d/60-omarchy-region.conf
else
  sudo rm -f /etc/environment.d/60-omarchy-region.conf
fi

# The registries only a config file points elsewhere: another edition's copies
# go while they match what it shipped, then this edition's fill in what is
# missing. Neither reaches through a symlink, as into a dotfiles repo.
shopt -s nullglob
real_home=$(realpath "$HOME")
chosen="$OMARCHY_PATH/default/regions/$region/home"
homes=()
for home in "$OMARCHY_PATH"/default/regions/*/home; do
  if [[ $home != "$chosen" ]]; then
    homes+=("$home")
  fi
done
if [[ -d $chosen ]]; then
  homes+=("$chosen")
fi
for home in "${homes[@]}"; do
  while IFS= read -r -d '' file; do
    seeded="$HOME/${file#"$home"/}"
    if [[ $(realpath -m "$seeded") != "$real_home/${file#"$home"/}" ]]; then
      continue
    elif [[ $home == "$chosen" ]]; then
      if [[ ! -e $seeded ]]; then
        mkdir -p "${seeded%/*}"
        cp "$file" "$seeded"
      fi
    elif cmp -s "$file" "$seeded"; then
      rm "$seeded"
    fi
  done < <(find "$home" -type f -print0)
done

# Its launchers, and its web app hotkeys, which Hyprland loads on reload.
omarchy-refresh-applications
if [[ -n ${HYPRLAND_INSTANCE_SIGNATURE:-} ]]; then
  hyprctl reload >/dev/null || true
fi

# The update runs the migrations and shell restart the refreshed packages need.
# The switch is done by now, so a failure there gives only the update's advice.
trap - ERR
OMARCHY_UPDATE_UNATTENDED=0 omarchy-update -y
