#!/bin/bash
#
# test-build - verify an already-published SBo package still builds on a target
# Slackware version inside a throwaway docker container. Resolves + builds its
# SBo deps from the local tree, caches built deps per image digest, reports
# per-package status and lints the target.
#
# Dependency-resolution, cache, and summary logic are adapted from sbo-batch-test
# (github: danixland). The overlay chroot is replaced by a docker container: the
# container IS the disposable environment, so no overlayfs.
#
# No em dashes in prose by author convention.

# =============================================================================
# CONFIG (do not edit here; real values live in the external config file)
# =============================================================================
SBO_TREE_CURRENT=""
SBO_TREE_STABLE=""
IMAGE_CURRENT=""
IMAGE_STABLE=""
LOG_ROOT="/var/log/sbo-test-build"
PKG_CACHE=""

TB_CONFIG="${TB_CONFIG:-$HOME/.config/sbo-testbuild/config}"
if [[ -f "$TB_CONFIG" ]]; then
  # shellcheck disable=SC1090
  source "$TB_CONFIG"
fi

TB_OVERRIDES="${TB_OVERRIDES:-$HOME/.config/sbo-testbuild/overrides}"

# =============================================================================
set -uo pipefail
# Not -e: a package build failing is a handled outcome, not a script crash.

# ---- flags / globals --------------------------------------------------------
USE_COLOR=1        # --no-color or non-TTY disables
DRY_RUN=0          # --dry-run: resolve + print order, do not build
ASSUME_YES=0       # --yes: skip the confirm prompt (still prints the order)
USE_CACHE=1        # --no-cache disables the dep cache for one run
VERSION_ID="current"   # "current" | "15.0"; set by --stable
TARGET_ARG=""

ACTIVE_TREE=""     # selected SBo tree (by version)
ACTIVE_IMAGE=""    # selected image tag (by version)
RUN_DIR=""         # timestamped log dir for this run

# Status tracking. Keyed by "category/prog". Parallel assoc arrays.
declare -A ST_STATUS=()
declare -A ST_REASON=()
declare -A ST_TIME=()
declare -A ST_README=()

usage() {
  cat <<'EOF'
test-build - verify an SBo package builds on a target Slackware in docker

USAGE:
  test-build [OPTIONS] <program-name>

OPTIONS:
  -h, --help    This text.
  --stable      Target Slackware 15.0 (image + tree). Default is -current.
  --dry-run     Resolve, apply overrides, print the build order, do not build.
  --yes         Skip the confirm prompt (the order is still printed first).
  --no-cache    Rebuild all deps this run, ignore/refresh the cache.
  --no-color    Disable ANSI color (auto-disabled when stdout is not a TTY).
EOF
}

parse_args() {
  while [[ $# -gt 0 ]]; do
    case "$1" in
      -h|--help) usage; exit 0 ;;
      --stable|15.0) VERSION_ID="15.0"; shift ;;
      --dry-run) DRY_RUN=1; shift ;;
      --yes) ASSUME_YES=1; shift ;;
      --no-cache) USE_CACHE=0; shift ;;
      --no-color) USE_COLOR=0; shift ;;
      -*) echo "Unknown option: $1" >&2; usage >&2; exit 2 ;;
      *)
        if [[ -n "$TARGET_ARG" ]]; then
          echo "Only one target accepted (got '$TARGET_ARG' and '$1')." >&2
          exit 2
        fi
        TARGET_ARG="$1"; shift ;;
    esac
  done
  if [[ -z "$TARGET_ARG" ]]; then
    echo "No target given." >&2; usage >&2; exit 2
  fi
}

init_color() {
  if [[ $USE_COLOR -eq 1 && -t 1 ]]; then
    C_RED=$'\e[31m'; C_GRN=$'\e[32m'; C_YEL=$'\e[33m'; C_RST=$'\e[0m'
  else
    C_RED=""; C_GRN=""; C_YEL=""; C_RST=""
  fi
}

# Map VERSION_ID to the active tree + image. No I/O, unit-testable.
select_version_paths() {
  if [[ "$VERSION_ID" == "15.0" ]]; then
    ACTIVE_TREE="$SBO_TREE_STABLE"; ACTIVE_IMAGE="$IMAGE_STABLE"
  else
    ACTIVE_TREE="$SBO_TREE_CURRENT"; ACTIVE_IMAGE="$IMAGE_CURRENT"
  fi
}

# require_config: the external config must exist and set the version's paths.
require_config() {
  if [[ ! -f "$TB_CONFIG" ]]; then
    cat >&2 <<EOF
No config file: $TB_CONFIG
Copy the example and edit it:

  mkdir -p "\$(dirname "$TB_CONFIG")"
  cp .extras/test-build-config.example "$TB_CONFIG"
  \${EDITOR:-vi} "$TB_CONFIG"
EOF
    exit 1
  fi
  select_version_paths
  if [[ -z "$ACTIVE_TREE" || -z "$ACTIVE_IMAGE" ]]; then
    echo "Config $TB_CONFIG is missing the tree/image for version '$VERSION_ID'." >&2
    exit 1
  fi
  if [[ ! -d "$ACTIVE_TREE" ]]; then
    echo "SBo tree for '$VERSION_ID' does not exist: $ACTIVE_TREE" >&2
    exit 1
  fi
}

main() {
  parse_args "$@"
  init_color
  require_config
}

main "$@"
