#!/usr/bin/env bash

set -euo pipefail

APP_DIR="${1:-}"
ARCHIVE_PATH="${2:-}"
ENV_FILE_PATH="${3:-}"

if [ -z "$APP_DIR" ] || [ -z "$ARCHIVE_PATH" ] || [ -z "$ENV_FILE_PATH" ]; then
  echo "Usage: deploy.sh <app_dir> <archive_path> <env_file_path>"
  exit 1
fi

if [ ! -f "$ENV_FILE_PATH" ]; then
  echo "Env file not found at $ENV_FILE_PATH"
  exit 1
fi

USE_SUDO=0
if command -v sudo >/dev/null 2>&1 && sudo -n true >/dev/null 2>&1; then
  USE_SUDO=1
fi

run_fs() {
  if [ "$USE_SUDO" -eq 1 ]; then
    sudo "$@"
  else
    "$@"
  fi
}

if [ -d "$APP_DIR" ]; then
  if [ ! -w "$APP_DIR" ]; then
    if [ "$USE_SUDO" -eq 0 ]; then
      echo "Deployment path exists but is not writable: $APP_DIR"
      echo "Use an SSH user that owns this directory, or set DEPLOY_PATH to a writable path in GitHub secrets."
      echo "Or configure passwordless sudo for this SSH user."
      exit 1
    fi
  fi
else
  APP_PARENT_DIR="$(dirname "$APP_DIR")"
  if [ ! -d "$APP_PARENT_DIR" ]; then
    echo "Parent directory does not exist: $APP_PARENT_DIR"
    echo "Set DEPLOY_PATH to an existing writable path in GitHub secrets."
    exit 1
  fi

  if [ ! -w "$APP_PARENT_DIR" ]; then
    if [ "$USE_SUDO" -eq 0 ]; then
      echo "Cannot create deployment directory. Parent is not writable: $APP_PARENT_DIR"
      echo "Set DEPLOY_PATH to a writable path in GitHub secrets."
      echo "Or configure passwordless sudo for this SSH user."
      exit 1
    fi
  fi

  run_fs mkdir -p "$APP_DIR"
fi

run_fs mkdir -p "$APP_DIR/storage/framework/cache"
run_fs mkdir -p "$APP_DIR/storage/framework/sessions"
run_fs mkdir -p "$APP_DIR/storage/framework/views"
run_fs mkdir -p "$APP_DIR/storage/logs"
run_fs mkdir -p "$APP_DIR/bootstrap/cache"

cd "$APP_DIR"

run_fs find "$APP_DIR" -mindepth 1 -maxdepth 1 \
  ! -name '.env' \
  ! -name 'storage' \
  ! -name 'bootstrap' \
  ! -name '.well-known' \
  -exec rm -rf {} +

run_fs cp "$ENV_FILE_PATH" "$APP_DIR/.env"

run_fs tar -xzf "$ARCHIVE_PATH" -C "$APP_DIR"
run_fs rm -f "$ARCHIVE_PATH" "$ENV_FILE_PATH"

if [ "$USE_SUDO" -eq 1 ]; then
  APP_OWNER="$(id -un)"
  APP_GROUP="$(id -gn)"
  sudo chown -R "$APP_OWNER:$APP_GROUP" "$APP_DIR"
fi

run_fs chmod -R ug+rw "$APP_DIR/storage" "$APP_DIR/bootstrap/cache"

php artisan optimize:clear
php artisan config:cache
php artisan route:cache || true
php artisan view:cache
php artisan migrate --force
