#!/usr/bin/env bash
#
#   npm run build:prod     test + production build + package, here on this Mac
#   npm run deploy:prod    ship that package (no second build)
#
# The build happens here because the server runs out of memory during
# `strapi build`. That build is only the admin panel (build/) - static
# JavaScript and CSS, no native binaries and no secrets baked in - so a Mac
# build runs on the Linux box unchanged. The API itself runs straight from
# src/, which the server pulls from GitLab at the same commit.
#
# The package is stamped with the commit it was built from; deploy:prod
# refuses to ship it if you have moved on since.

set -euo pipefail

APP="wedig-strapi"
BUILD_DIR="build"
OUT_DIR=".deploy"          # gitignored

cd "$(git -C "$(dirname "$0")" rev-parse --show-toplevel)"
step() { printf '\n\033[1;36m==> %s\033[0m\n' "$*"; }
fail() { printf '\n\033[1;31mSTOPPED: %s\033[0m\n' "$*" >&2; exit 1; }

step "Checking this copy"
[[ -z "$(git status --porcelain --untracked-files=no)" ]] \
  || fail "Uncommitted changes. Commit first - a build must match a commit exactly, or it cannot be traced or rolled back."
SHA="$(git rev-parse HEAD)"
echo "Building $(git log --oneline -1)"

step "Tests"
npm test

step "Building for production"
rm -rf "$BUILD_DIR"
NODE_ENV=production npm run build

step "Packaging"
rm -rf "$OUT_DIR" && mkdir -p "$OUT_DIR"
ARCHIVE="$OUT_DIR/$APP-${SHA:0:7}.tar.gz"
COPYFILE_DISABLE=1 tar --no-xattrs -czf "$ARCHIVE" \
  "$BUILD_DIR"
printf 'SHA=%q\nARCHIVE=%q\nBUILT_AT=%q\n' "$SHA" "$ARCHIVE" "$(date '+%Y-%m-%d %H:%M')" > "$OUT_DIR/release.env"

printf '\n\033[1;32mBuilt %s (%s).\033[0m  Next: npm run deploy:prod\n' "$(git log --oneline -1)" "$(du -h "$ARCHIVE" | cut -f1)"
