#!/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"
CURRENT_LINK="$BASE_DIR/current"
TARGET_RELEASE="${1:-}"

if [[ ! -L "$CURRENT_LINK" ]]; then
  echo "Current symlink not found at $CURRENT_LINK"
  exit 1
fi

CURRENT_TARGET="$(readlink "$CURRENT_LINK")"

if [[ -z "$TARGET_RELEASE" ]]; then
  mapfile -t RELEASES < <(ls -1dt "$RELEASES_DIR"/* 2>/dev/null || true)
  if [[ "${#RELEASES[@]}" -lt 2 ]]; then
    echo "No previous release found in $RELEASES_DIR"
    exit 1
  fi

  for release in "${RELEASES[@]}"; do
    if [[ "$release" != "$CURRENT_TARGET" ]]; then
      TARGET_RELEASE="$release"
      break
    fi
  done
fi

if [[ ! -d "$TARGET_RELEASE" ]]; then
  echo "Target release does not exist: $TARGET_RELEASE"
  exit 1
fi

php "$CURRENT_LINK/artisan" down --retry=60 || true
ln -sfn "$TARGET_RELEASE" "$CURRENT_LINK"
php "$CURRENT_LINK/artisan" optimize
php "$CURRENT_LINK/artisan" queue:restart || true
php "$CURRENT_LINK/artisan" up || true

echo "Rollback done."
echo "Current symlink: $CURRENT_LINK -> $(readlink "$CURRENT_LINK")"
