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

SCRIPT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
ROOT_DIR=$(cd "$SCRIPT_DIR/../.." && pwd)
BACKEND_DIR="$ROOT_DIR/apps/backend"
WEB_DIR="$ROOT_DIR/apps/web"
EXTENSION_DIR="$ROOT_DIR/apps/extension/haixun-threads-sync"
ARTIFACT_DIR="$SCRIPT_DIR/artifacts"
timestamp=$(date -u +%Y%m%dT%H%M%SZ)
revision=$(git -C "$ROOT_DIR" rev-parse --short HEAD 2>/dev/null || printf unknown)
if ! git -C "$ROOT_DIR" diff --quiet --ignore-submodules -- 2>/dev/null || [[ -n $(git -C "$ROOT_DIR" ls-files --others --exclude-standard 2>/dev/null) ]]; then
  revision="$revision-dirty"
fi
release_id="harbor-$timestamp-$revision"
stage=$(mktemp -d "/tmp/${release_id}.XXXXXX")
trap 'rm -rf "$stage"' EXIT

mkdir -p "$stage/bin" "$stage/web" "$stage/migrations" "$stage/scripts/threads-profile" "$ARTIFACT_DIR"

if [[ ${SKIP_TESTS:-0} != 1 ]]; then
	(cd "$BACKEND_DIR" && go test ./... && go vet ./...)
fi

(cd "$WEB_DIR" && npm ci)
if [[ ${SKIP_TESTS:-0} != 1 ]]; then
	(cd "$WEB_DIR" && npm test)
fi

printf '%s\n' "building Linux amd64 gateway and worker"
(cd "$BACKEND_DIR" && CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -trimpath -ldflags='-s -w' -o "$stage/bin/gateway" .)
(cd "$BACKEND_DIR" && CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -trimpath -ldflags='-s -w' -o "$stage/bin/worker" ./cmd/worker)
(cd "$BACKEND_DIR" && CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -trimpath -ldflags='-s -w' -o "$stage/bin/seeder" ./cmd/seeder)
GOBIN="$stage/bin" CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go install -tags mongodb github.com/golang-migrate/migrate/v4/cmd/migrate@v4.18.3

printf '%s\n' "building static web"
(cd "$WEB_DIR" && VITE_API_BASE= npm run build)
cp -a "$WEB_DIR/dist/." "$stage/web/"
printf '%s\n' "building Chrome extension zip"
python3 - "$EXTENSION_DIR" "$stage/web/downloads/haixun-threads-sync.zip" <<'PY'
import pathlib
import sys
import zipfile

source = pathlib.Path(sys.argv[1])
output = pathlib.Path(sys.argv[2])
output.parent.mkdir(parents=True, exist_ok=True)
with zipfile.ZipFile(output, "w", zipfile.ZIP_DEFLATED) as archive:
    for path in sorted(source.rglob("*")):
        if path.is_file():
            archive.write(path, path.relative_to(source.parent))

with zipfile.ZipFile(output) as archive:
    archived_worker = archive.read(f"{source.name}/service-worker.js")
if archived_worker != (source / "service-worker.js").read_bytes():
    raise SystemExit("extension service-worker.js does not match source")
PY
cp -a "$BACKEND_DIR/generate/database/mongo/." "$stage/migrations/"

printf '%s\n' "bundling threads-profile scrape script"
(cd "$BACKEND_DIR/scripts/threads-profile" && npm ci --omit=dev)
(cd "$BACKEND_DIR/scripts/threads-profile" && PLAYWRIGHT_HOST_PLATFORM_OVERRIDE=ubuntu24.04-x64 PLAYWRIGHT_BROWSERS_PATH=0 npx playwright install chromium-headless-shell)
cp -a "$BACKEND_DIR/scripts/threads-profile/scrape.mjs" "$stage/scripts/threads-profile/"
cp -a "$BACKEND_DIR/scripts/threads-profile/package.json" "$stage/scripts/threads-profile/"
tar -C "$BACKEND_DIR/scripts/threads-profile/node_modules/playwright-core/.local-browsers" -czf "$stage/scripts/threads-profile/playwright-browsers.tar.gz" .
(cd "$BACKEND_DIR/scripts/threads-profile" && tar --exclude='node_modules/playwright-core/.local-browsers' -cf - node_modules) | tar -C "$stage/scripts/threads-profile" -xf -

cat > "$stage/release.txt" <<EOF
release=$release_id
revision=$revision
built_at=$timestamp
goos=linux
goarch=amd64
EOF
(cd "$stage" && sha256sum bin/gateway bin/worker bin/seeder bin/migrate web/index.html web/downloads/haixun-threads-sync.zip > manifest.sha256)
find "$stage" -type d -exec chmod 0755 {} +
find "$stage" -type f -exec chmod 0644 {} +
chmod 0755 "$stage/bin/gateway" "$stage/bin/worker" "$stage/bin/seeder" "$stage/bin/migrate"

artifact="$ARTIFACT_DIR/$release_id.tar.gz"
tar -C "$stage" -czf "$artifact" .
sha256sum "$artifact" > "$artifact.sha256"
printf '%s\n' "$artifact"
