#!/usr/bin/env bash
set -euo pipefail

REMOTE="github-public"
BRANCH="main"
LOCAL_DIR="$(cd "$(dirname "$0")" && pwd)"
PUBLISH_DIR="${LOCAL_DIR}/publish"
MANIFEST="${PUBLISH_DIR}/manifest"
DRY_RUN=false

for arg in "$@"; do
    case "$arg" in
        --dry-run) DRY_RUN=true ;;
        *) echo "Unknown argument: $arg"; exit 1 ;;
    esac
done

if ! git -C "$LOCAL_DIR" remote get-url "$REMOTE" &>/dev/null; then
    echo "ERROR: remote '${REMOTE}' not found."
    echo "  git remote add ${REMOTE} https://github.com/brutsalvadi/bincio-activity.git"
    exit 1
fi
if [[ -n "$(git -C "$LOCAL_DIR" status --porcelain --untracked-files=no)" ]]; then
    echo "ERROR: uncommitted changes. Commit or stash first."
    exit 1
fi
if [[ ! -f "$MANIFEST" ]]; then
    echo "ERROR: manifest not found at ${MANIFEST}"
    exit 1
fi

# Collect file list AND stage into temp dir before touching git state.
# Both must happen here — `git rm -rf .` removes the manifest itself,
# so it can't be re-read during the orphan branch step.
STAGING="$(mktemp -d)"
trap 'rm -rf "$STAGING"' EXIT
FILES=()

while IFS= read -r relpath || [[ -n "$relpath" ]]; do
    [[ -z "$relpath" || "$relpath" == \#* ]] && continue
    override="${PUBLISH_DIR}/${relpath}"
    original="${LOCAL_DIR}/${relpath}"
    dest="${STAGING}/${relpath}"
    mkdir -p "$(dirname "$dest")"
    if [[ -f "$override" ]]; then
        cp "$override" "$dest"
    elif [[ -f "$original" ]]; then
        cp "$original" "$dest"
    else
        echo "ERROR: '${relpath}' in manifest but not found (no override, no original)"
        exit 1
    fi
    FILES+=("$relpath")
done < "$MANIFEST"

echo "Files to be published:"
printf '  %s\n' "${FILES[@]}"

if $DRY_RUN; then
    echo ""
    echo "Dry run complete. No changes made."
    exit 0
fi

# Create orphan branch, wipe working tree, restore only manifest files
git -C "$LOCAL_DIR" checkout --orphan _public_tmp
git -C "$LOCAL_DIR" rm -rf . --quiet
cp -r "${STAGING}/." "${LOCAL_DIR}/"

TIMESTAMP="$(date -u +%Y-%m-%dT%H:%M:%SZ)"
# Add only manifest files — never picks up untracked files outside the manifest
for relpath in "${FILES[@]}"; do
    git -C "$LOCAL_DIR" add -- "$relpath"
done
git -C "$LOCAL_DIR" commit -m "Published ${TIMESTAMP}"
git -C "$LOCAL_DIR" push --force "$REMOTE" "HEAD:${BRANCH}"

git -C "$LOCAL_DIR" checkout main
git -C "$LOCAL_DIR" branch -D _public_tmp

echo ""
echo "Done: $(git -C "$LOCAL_DIR" remote get-url "$REMOTE")"
