#!/usr/bin/env bash
# Copies the app's public files into the website folder Hostinger serves.
#   WEB=~/domains/karanshah.ca/public_html/shreeji bash deploy/sync-public.sh
# The folder is remembered in deploy/.web-root after the first run, so later runs need no WEB=.
# index.php is pointed at this app folder automatically, wherever the two folders are.
set -euo pipefail
APP_DIR="$(cd "$(dirname "$0")/.." && pwd)"
SAVED="$APP_DIR/deploy/.web-root"
if [ -z "${WEB:-}" ] && [ -f "$SAVED" ]; then WEB=$(cat "$SAVED"); fi
WEB=${WEB:-"$APP_DIR/../public_html"}
mkdir -p "$WEB"
WEB="$(cd "$WEB" && pwd)"
echo "$WEB" > "$SAVED"

REL=$(realpath --relative-to="$WEB" "$APP_DIR")
sed "s#__DIR__.'/../laravel-app'#__DIR__.'/$REL'#" "$APP_DIR/deploy/public_html-index.php" > "$WEB/index.php"
for f in .htaccess favicon.ico robots.txt; do
  if [ -f "$APP_DIR/public/$f" ]; then cp "$APP_DIR/public/$f" "$WEB/"; fi
done
for d in build css js fonts brand; do
  if [ -d "$APP_DIR/public/$d" ]; then rm -rf "${WEB:?}/$d" && cp -r "$APP_DIR/public/$d" "$WEB/$d"; fi
done
echo "Website folder updated: $WEB (app at $REL)"
