#!/usr/bin/env bash
set -euo pipefail

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
DIST_DIR="${ROOT_DIR}/dist"
PUBLIC_DOWNLOADS="${ROOT_DIR}/public/downloads"
VERSION="${1:-$(date +%Y.%m.%d)}"
PACKAGE_NAME="cms-ck-${VERSION}.zip"
INCLUDE_VENDOR="${INCLUDE_VENDOR:-1}"

mkdir -p "${DIST_DIR}"
mkdir -p "${PUBLIC_DOWNLOADS}"

tmpdir="$(mktemp -d)"
trap 'rm -rf "${tmpdir}"' EXIT

RSYNC_EXCLUDES=(
  --exclude ".git"
  --exclude "dist"
  --exclude "cache"
  --exclude "tenants"
  --exclude "public/uploads"
  --exclude ".env"
)

if [[ "${INCLUDE_VENDOR}" != "1" ]]; then
  RSYNC_EXCLUDES+=(--exclude "vendor")
fi

rsync -a "${RSYNC_EXCLUDES[@]}" "${ROOT_DIR}/" "${tmpdir}/cms-ck"

(
  cd "${tmpdir}"
  zip -r "${DIST_DIR}/${PACKAGE_NAME}" "cms-ck" >/dev/null
)

cp "${DIST_DIR}/${PACKAGE_NAME}" "${PUBLIC_DOWNLOADS}/${PACKAGE_NAME}"
ln -sfn "${PACKAGE_NAME}" "${PUBLIC_DOWNLOADS}/latest.zip"

sha256="$(sha256sum "${PUBLIC_DOWNLOADS}/${PACKAGE_NAME}" | awk '{print $1}')"
size_bytes="$(stat -c%s "${PUBLIC_DOWNLOADS}/${PACKAGE_NAME}")"
cat > "${PUBLIC_DOWNLOADS}/release.json" <<EOFJSON
{
  "version": "${VERSION}",
  "filename": "${PACKAGE_NAME}",
  "sha256": "${sha256}",
  "size_bytes": ${size_bytes},
  "generated_at": "$(date -u +"%Y-%m-%dT%H:%M:%SZ")"
}
EOFJSON

echo "Release package created: ${DIST_DIR}/${PACKAGE_NAME}"
echo "Published to: ${PUBLIC_DOWNLOADS}/${PACKAGE_NAME}"
if [[ "${INCLUDE_VENDOR}" == "1" ]]; then
  echo "Included vendor/: yes"
else
  echo "Included vendor/: no"
fi
