#!/usr/bin/env bash
set -euo pipefail

root_dir=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)
image=${BOT_FORGE_APT_TEST_IMAGE:-ubuntu:24.04}

docker run --rm -v "$root_dir:/workspace:ro" "$image" bash -lc '
  set -euo pipefail
  command -v apt-get >/dev/null
  test -x /workspace/target/debug/bot-forge
  apt-get update >/dev/null
  DEBIAN_FRONTEND=noninteractive apt-get install -y ca-certificates >/dev/null
  work=$(mktemp -d)
  trap "rm -rf \"$work\"" EXIT
  source_file="$work/bot-forge.sources"
  config="$work/config.toml"
  case "$(dpkg --print-architecture)" in
    amd64) mirror_uri="https://archive.ubuntu.com/ubuntu" ;;
    arm64) mirror_uri="https://ports.ubuntu.com/ubuntu-ports" ;;
    *) printf "unsupported APT test architecture\n" >&2; exit 1 ;;
  esac
  cp /workspace/bot-forge.toml "$config"
  cat >> "$config" <<EOF

[apt_mirror]
uri = "$mirror_uri"
suites = ["{codename}", "{codename}-updates", "{codename}-security"]
components = ["main", "universe"]
architectures = ["{architecture}"]
source_file = "$source_file"
EOF

  /workspace/target/debug/bot-forge apt-mirror show --config "$config" > "$work/preview"
  awk '\''
    /^bot-forge\.sources$/ { capture=1; next }
    capture && /^  / { sub(/^  /, ""); print; next }
    capture { exit }
  '\'' "$work/preview" > "$work/generated.sources"
  test -s "$work/generated.sources"
  mkdir -p "$work/lists/partial"
  apt-get -o APT::Update::Error-Mode=any -o APT::Sandbox::User=root -o "Dir::Etc::sourcelist=$work/generated.sources" -o Dir::Etc::sourceparts=- -o "Dir::State::lists=$work/lists" update

  printf "original\n" > "$source_file"
  printf "y\n" | script -q -c "/workspace/target/debug/bot-forge apt-mirror apply --config $config" /dev/null
  test -s "$source_file"
  test -f "$source_file.bot-forge.bak"
  printf "y\n" | script -q -c "/workspace/target/debug/bot-forge apt-mirror restore --config $config" /dev/null
  test "$(cat "$source_file")" = original
'
