#!/usr/bin/env bash

# omarchy:summary=Set the Omarchy package channel.
# omarchy:args=<stable|dev>
# omarchy:requires-sudo=true

# Based: the channel is the based-* apt source the machine tracks, dev
# (based-ddev, based-udev, based-u26dev) or stable (based-d13, based-u24,
# based-u26). Switching renames that one source and points its URL at the
# other channel, refreshes apt, and runs the update, which takes the omarchy
# and based packages from there. Leaving dev downgrades nothing: a package
# newer than stable stays until stable catches up.

set -euo pipefail

usage() { echo "Usage: omarchy-channel-set <stable|dev>"; }
fail() { echo "Error: $*" >&2; exit 1; }

(( $# > 0 )) || { usage; exit 1; }

channel="$1"
case "$channel" in
  stable | dev) ;;
  *)
    echo "Unknown channel: $channel" >&2
    usage >&2
    exit 1
    ;;
esac

apt_dir=${OMARCHY_APT_DIR:-/etc/apt}
current_file=""
for file in "$apt_dir"/sources.list.d/based-*; do
  case "${file##*/}" in
    based-ddev.list | based-d13.list | based-udev.list | based-u24.list | based-u26dev.list | based-u26.list | \
      based-ddev.sources | based-d13.sources | based-udev.sources | based-u24.sources | based-u26dev.sources | based-u26.sources)
      current_file=$file
      break
      ;;
  esac
done
[[ -n $current_file ]] || fail "no Based apt channel in $apt_dir/sources.list.d"

current_name=${current_file##*/}
current=${current_name%.*}
case "$current" in
  based-ddev | based-d13) stable=based-d13 dev=based-ddev ;;
  based-udev | based-u24) stable=based-u24 dev=based-udev ;;
  based-u26dev | based-u26) stable=based-u26 dev=based-u26dev ;;
esac
target=${!channel}

if [[ $current == "$target" ]]; then
  echo "Already on the $channel channel ($target)."
else
  target_file="$apt_dir/sources.list.d/$target.${current_name##*.}"
  # The channel is the last segment of the repository URL (.../deb/based-ddev),
  # so only a whole segment is rewritten; the suite and the keyring stay.
  sed -E "s#/${current}([[:space:]/]|\$)#/${target}\\1#g" "$current_file" | sudo tee "$target_file" >/dev/null
  sudo chmod 0644 "$target_file"
  sudo rm -f "$current_file"
  echo "Switched from $current to $target."
fi

sudo apt-get update
apt-cache policy | grep -F "/$target " || true

omarchy-update -y
