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

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SOURCE_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"

if [[ "$SOURCE_DIR" == *"/releases/"* ]]; then
  BASE_DIR="${SOURCE_DIR%/releases/*}"
else
  BASE_DIR="$(cd "$SOURCE_DIR/.." && pwd)"
fi

RELEASES_DIR="$BASE_DIR/releases"
SHARED_DIR="$BASE_DIR/shared"
CURRENT_LINK="$BASE_DIR/current"
RELEASE_ID="$(date +%Y%m%d%H%M%S)"
NEW_RELEASE_DIR="$RELEASES_DIR/$RELEASE_ID"
PREVIOUS_RELEASE=""

mkdir -p "$RELEASES_DIR" "$SHARED_DIR"
mkdir -p \
  "$SHARED_DIR/storage/app" \
  "$SHARED_DIR/storage/firebase" \
  "$SHARED_DIR/storage/framework/cache" \
  "$SHARED_DIR/storage/framework/sessions" \
  "$SHARED_DIR/storage/framework/views" \
  "$SHARED_DIR/storage/logs" \
  "$SHARED_DIR/bootstrap/cache"

if [[ -L "$CURRENT_LINK" ]]; then
  PREVIOUS_RELEASE="$(readlink "$CURRENT_LINK")"
fi

if [[ ! -f "$SHARED_DIR/.env" ]]; then
  if [[ -f "$SOURCE_DIR/.env" ]]; then
    cp "$SOURCE_DIR/.env" "$SHARED_DIR/.env"
  else
    echo "Missing shared/.env and source .env. Create $SHARED_DIR/.env first."
    exit 1
  fi
fi

mkdir -p "$NEW_RELEASE_DIR"
if command -v rsync >/dev/null 2>&1; then
  rsync -a --delete \
    --exclude ".git" \
    --exclude "storage/*" \
    --exclude "bootstrap/cache/*" \
    "$SOURCE_DIR/" "$NEW_RELEASE_DIR/"
else
  cp -R "$SOURCE_DIR/." "$NEW_RELEASE_DIR/"
  rm -rf "$NEW_RELEASE_DIR/.git" "$NEW_RELEASE_DIR/storage" "$NEW_RELEASE_DIR/bootstrap/cache"
fi

rm -rf "$NEW_RELEASE_DIR/storage"
mkdir -p "$NEW_RELEASE_DIR/bootstrap"
rm -rf "$NEW_RELEASE_DIR/bootstrap/cache"
ln -sfn "$SHARED_DIR/storage" "$NEW_RELEASE_DIR/storage"
ln -sfn "$SHARED_DIR/bootstrap/cache" "$NEW_RELEASE_DIR/bootstrap/cache"
ln -sfn "$SHARED_DIR/.env" "$NEW_RELEASE_DIR/.env"

if [[ -L "$CURRENT_LINK" ]]; then
  php "$CURRENT_LINK/artisan" down --retry=60 || true
fi

pushd "$NEW_RELEASE_DIR" >/dev/null
composer install --no-dev --prefer-dist --no-interaction --optimize-autoloader
php artisan config:clear
php artisan route:clear
php artisan view:clear
php artisan migrate --force
php artisan storage:link || true
php artisan optimize
popd >/dev/null

ln -sfn "$NEW_RELEASE_DIR" "$CURRENT_LINK"

php "$CURRENT_LINK/artisan" queue:restart || true
php "$CURRENT_LINK/artisan" up || true

if [[ -x "$CURRENT_LINK/scripts/preflight_cpanel.sh" ]]; then
  echo "Running post-deploy preflight..."
  "$CURRENT_LINK/scripts/preflight_cpanel.sh"
fi

if [[ -n "${LINEUP_SMOKE_URL:-}" && -x "$CURRENT_LINK/scripts/smoke_web.sh" ]]; then
  echo "Running post-deploy smoke on ${LINEUP_SMOKE_URL}..."
  "$CURRENT_LINK/scripts/smoke_web.sh" "$LINEUP_SMOKE_URL"
fi

if [[ -n "$PREVIOUS_RELEASE" ]]; then
  echo "$PREVIOUS_RELEASE" > "$BASE_DIR/.previous_release"
fi

echo "Release deployed: $NEW_RELEASE_DIR"
echo "Current symlink: $CURRENT_LINK -> $(readlink "$CURRENT_LINK")"
