#!/bin/sh
# Root helper: point apt at apt/stable or apt/dev. Foam never applies a
# .deb from inside the app; `` `channel `` may try `sudo -n` this script.
#
#   sudo /usr/lib/foam/apt-channel stable
#   sudo /usr/lib/foam/apt-channel dev
set -e

CHANNEL="$(printf '%s' "${1:-}" | tr '[:upper:]' '[:lower:]')"
case "$CHANNEL" in
  stable|dev) ;;
  *)
    echo "foam-apt-channel: usage: foam-apt-channel stable|dev" >&2
    exit 2
    ;;
esac

SOURCES="${FOAM_APT_SOURCES:-/etc/apt/sources.list.d/foam.sources}"
LIST="/etc/apt/sources.list.d/foam.list"
ORIGIN_FILE="/opt/Foam/resources/linux/apt-origin.txt"
ORIGIN="${FOAM_APT_ORIGIN:-}"
if [ -z "$ORIGIN" ] && [ -f "$ORIGIN_FILE" ]; then
  ORIGIN="$(head -n 1 "$ORIGIN_FILE" | tr -d '\r')"
fi
if [ -z "$ORIGIN" ]; then
  ORIGIN="https://pub-1f9d299deece4a2e916123fe5e215038.r2.dev"
fi
ORIGIN="${ORIGIN%/}"

write_sources() {
  cat > "$1" <<EOF
Types: deb
URIs: ${ORIGIN}/apt/${CHANNEL}
Suites: ${CHANNEL}
Components: main
Architectures: amd64
Signed-By: /usr/share/keyrings/foam-archive-keyring.gpg
EOF
}

rewrite_file() {
  file="$1"
  tmp="$(mktemp)"
  sed -E \
    -e "s#(/apt/)(stable|dev)\\b#\\1${CHANNEL}#g" \
    -e "s#^(Suites:)[[:space:]]*(stable|dev)\\s*\$#\\1 ${CHANNEL}#" \
    "$file" > "$tmp"
  mv "$tmp" "$file"
}

if [ -f "$SOURCES" ]; then
  rewrite_file "$SOURCES"
elif [ -f "$LIST" ]; then
  rewrite_file "$LIST"
else
  write_sources "$SOURCES"
fi

chmod 644 "$SOURCES" 2>/dev/null || true
[ -f "$LIST" ] && chmod 644 "$LIST" || true
echo "Foam apt channel: $CHANNEL"
