#!/usr/bin/env bash

set -euo pipefail

source_dir="${1:-}"
output_dir="${2:-}"

if [[ -z "$source_dir" || -z "$output_dir" ]]; then
  echo "Usage: $0 SOURCE_DIR OUTPUT_DIR" >&2
  exit 64
fi

if [[ ! -d "$source_dir/connection" ]]; then
  echo "Missing connection directory: $source_dir/connection" >&2
  exit 66
fi

if [[ -e "$output_dir" ]]; then
  echo "Output path already exists: $output_dir" >&2
  exit 73
fi

install -d -m 0755 "$output_dir"
cp -a "$source_dir/connection" "$output_dir/connection"

game_count=0
while IFS= read -r -d '' index_file; do
  game_dir="$(dirname "$index_file")"
  cp -a "$game_dir" "$output_dir/$(basename "$game_dir")"
  game_count=$((game_count + 1))
done < <(find "$source_dir" -mindepth 2 -maxdepth 2 -type f -name index.html -print0)

if (( game_count == 0 )); then
  echo "No top-level game directories containing index.html were found." >&2
  exit 65
fi

find "$output_dir" -type d -exec chmod 0755 {} +
find "$output_dir" -type f -exec chmod 0644 {} +

echo "Built release with $game_count games in $output_dir"
