#!/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"
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/"
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)
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/"
cp -a "$BACKEND_DIR/scripts/threads-profile/node_modules" "$stage/scripts/threads-profile/"

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 > 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"
