#!/usr/bin/env bash
# ─────────────────────────────────────────────────────────────────────────────
# SureRightStay — Production storage setup script
#
# Run this ONCE after every deployment (or whenever storage needs resetting).
#
# Usage:
#   cd /var/www/html/portalapi
#   bash deployment/storage-setup.sh
#
# The script assumes it is run from the portalapi root directory.
# ─────────────────────────────────────────────────────────────────────────────

set -e

STORAGE_PUBLIC="storage/app/public"
WEB_USER="${1:-www-data}"   # Pass nginx/apache user as first arg, default www-data

echo "=== SRS Storage Setup ==="
echo "Working directory: $(pwd)"
echo "Web user: ${WEB_USER}"
echo ""

# ── 1. Create required subdirectories ────────────────────────────────────────
echo "[1/5] Creating storage subdirectories..."
mkdir -p "${STORAGE_PUBLIC}/property-images"
mkdir -p "${STORAGE_PUBLIC}/profile-pictures"
mkdir -p "${STORAGE_PUBLIC}/documents/verification"
mkdir -p "${STORAGE_PUBLIC}/documents/identity"
mkdir -p "${STORAGE_PUBLIC}/documents/property_document"
mkdir -p "${STORAGE_PUBLIC}/documents/other"
mkdir -p "${STORAGE_PUBLIC}/watermarks"
mkdir -p "storage/app/private"
mkdir -p "storage/framework/cache"
mkdir -p "storage/framework/sessions"
mkdir -p "storage/framework/views"
mkdir -p "storage/logs"
echo "    Done."

# ── 2. Set directory permissions ──────────────────────────────────────────────
echo "[2/5] Setting directory permissions (755)..."
find storage -type d -exec chmod 755 {} \;
find bootstrap/cache -type d -exec chmod 755 {} \;
echo "    Done."

# ── 3. Set file permissions ───────────────────────────────────────────────────
echo "[3/5] Setting file permissions (644)..."
find "${STORAGE_PUBLIC}" -type f -exec chmod 644 {} \;
echo "    Done."

# ── 4. Set ownership ──────────────────────────────────────────────────────────
echo "[4/5] Setting ownership to ${WEB_USER}..."
chown -R "${WEB_USER}:${WEB_USER}" storage
chown -R "${WEB_USER}:${WEB_USER}" bootstrap/cache
echo "    Done."

# ── 5. Create / refresh the public storage symlink ───────────────────────────
echo "[5/5] Creating storage symlink (php artisan storage:link)..."
# Remove broken symlink if it exists
if [ -L "public/storage" ] && [ ! -e "public/storage" ]; then
    echo "    Removing broken symlink..."
    rm public/storage
fi
php artisan storage:link --force
echo "    Done."

echo ""
echo "=== Storage setup complete ==="
echo ""
echo "IMPORTANT — Nginx production fix:"
echo "  Add the following to your Nginx server {} config so uploaded images"
echo "  are served directly from storage/app/public (bypasses symlink + 403):"
echo ""
echo "  location ^~ /storage/ {"
echo "      alias $(pwd)/${STORAGE_PUBLIC}/;"
echo "      try_files \$uri =404;"
echo "      expires 1y;"
echo "      add_header Cache-Control \"public, immutable\";"
echo "  }"
echo ""
echo "  Then reload nginx: sudo nginx -t && sudo systemctl reload nginx"
