#!/usr/bin/env bash
# Pre-builds bare git repos for bundled apps so the install script
# doesn't need to run any git commands.
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
ROOT="$SCRIPT_DIR/.."
APPS_DIR="$ROOT/apps"
OUT_DIR="$ROOT/dist/repos"

rm -rf "$OUT_DIR"
mkdir -p "$OUT_DIR"

for app_dir in "$APPS_DIR"/*/; do
  app=$(basename "$app_dir")
  [ -f "$app_dir/package.json" ] || continue

  tmp=$(mktemp -d)
  tar -C "$app_dir" \
    --exclude='node_modules' \
    --exclude='logs' \
    --exclude='current' \
    --exclude='[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]-[0-9][0-9][0-9][0-9][0-9][0-9]' \
    -cf - . | tar -C "$tmp" -xf -

  git -C "$tmp" init -b main -q
  git -C "$tmp" add -A
  git -C "$tmp" -c user.name=toes -c user.email=toes@localhost commit -q -m "install"
  git clone --bare -q "$tmp" "$OUT_DIR/$app.git"
  git -C "$OUT_DIR/$app.git" config http.receivepack true

  rm -rf "$tmp"
  echo "   $app"
done

echo ">> Bare repos built in dist/repos/"
