#!/usr/bin/env bash
# Build the app image, pull the postgres image, and save BOTH to a single tarball
# you can copy to any other machine that only has Docker installed.
#
# Usage:  bash docker-build-and-save.sh
# Output: ./DockerImages/atapoly-cbt-images.tar  +  docker-compose.yml

set -e

OUT_DIR="DockerImages"
mkdir -p "$OUT_DIR"

echo "==> Building app image (atapoly-cbt-app:latest)…"
docker compose build app

echo "==> Pulling postgres:15-alpine…"
docker pull postgres:15-alpine

echo "==> Saving both images to $OUT_DIR/atapoly-cbt-images.tar…"
docker save -o "$OUT_DIR/atapoly-cbt-images.tar" \
  atapoly-cbt-app:latest \
  postgres:15-alpine

cp docker-compose.yml "$OUT_DIR/docker-compose.yml"

cat > "$OUT_DIR/README.txt" <<'EOF'
ATAPOLY CBT — Docker Bundle
============================

On the target machine (only Docker required):

  1. Copy this folder (DockerImages/) to the machine.
  2. Load the images:
       docker load -i atapoly-cbt-images.tar
  3. Start the stack:
       docker compose up -d
  4. Open the app:
       http://<machine-ip>:3001

Stop:        docker compose down
Stop + wipe: docker compose down -v   (deletes the database!)
Logs:        docker compose logs -f app
EOF

echo ""
echo "✅ Done."
echo "   Bundle:  $OUT_DIR/atapoly-cbt-images.tar  ($(du -h "$OUT_DIR/atapoly-cbt-images.tar" | cut -f1))"
echo "   Compose: $OUT_DIR/docker-compose.yml"
echo ""
echo "Copy the entire '$OUT_DIR' folder to any machine that has Docker, then run:"
echo "   docker load -i atapoly-cbt-images.tar && docker compose up -d"
