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

APP="/home/cghggujarat/laravel_apps/cghg_portal"
PREVIEW="/home/cghggujarat/public_html/new/portalarea-laravel-preview"
OLD="/home/cghggujarat/public_html/website"
PHP82="/opt/cpanel/ea-php82/root/usr/bin/php"
OWNER="cghggujarat:cghggujarat"
STAMP="$(date +%Y%m%d-%H%M%S)"
BACKUP="$APP/_migration_backups/website-old-exact-v9-$STAMP"

fail(){ echo "ERROR: $*" >&2; exit 1; }
say(){ printf '\n===== %s =====\n' "$1"; }

[ -d "$APP" ] || fail "Laravel app missing: $APP"
[ -f "$APP/artisan" ] || fail "artisan missing"
[ -d "$OLD" ] || fail "Old website folder missing: $OLD"
[ -d "$PREVIEW" ] || fail "Preview public folder missing: $PREVIEW"

cd "$APP"

say "1/9 BACKUP CURRENT LARAVEL WEBSITE"
mkdir -p "$BACKUP"
[ -d resources/views/website ] && cp -a resources/views/website "$BACKUP/website-views.before"
cp -a routes/web.php "$BACKUP/web.php.before"

cat > "$BACKUP/ROLLBACK.sh" <<ROLLBACK
#!/usr/bin/env bash
set -e
APP="$APP"
BACKUP="$BACKUP"

if [ -d "\$BACKUP/website-views.before" ]; then
    rm -rf "\$APP/resources/views/website"
    cp -a "\$BACKUP/website-views.before" "\$APP/resources/views/website"
fi

cp -af "\$BACKUP/web.php.before" "\$APP/routes/web.php"
chown -R $OWNER "\$APP/resources/views/website" "\$APP/routes/web.php" 2>/dev/null || true
cd "\$APP"
runuser -u cghggujarat -- env HOME=/home/cghggujarat "$PHP82" artisan optimize:clear >/dev/null 2>&1 || true
echo "ROLLBACK COMPLETE"
ROLLBACK
chmod 750 "$BACKUP/ROLLBACK.sh"

rollback_on_error(){
    code=$?
    echo
    echo "V9 FAILED - restoring previous Laravel website..."
    bash "$BACKUP/ROLLBACK.sh" || true
    exit "$code"
}
trap rollback_on_error ERR

say "2/9 DETECT OLD WEBSITE ENTRY FILE"
OLD_INDEX=""
for f in "$OLD/index.php" "$OLD/index.html" "$OLD/index.htm"; do
    if [ -f "$f" ]; then
        OLD_INDEX="$f"
        break
    fi
done
[ -n "$OLD_INDEX" ] || fail "No index.php/index.html found in $OLD"
echo "OLD_INDEX=$OLD_INDEX"

say "3/9 COPY OLD WEBSITE STATIC ASSETS EXACTLY"

APP_ASSETS="$APP/public/assets/website-legacy"
PREVIEW_ASSETS="$PREVIEW/assets/website-legacy"

rm -rf "$APP_ASSETS" "$PREVIEW_ASSETS"
mkdir -p "$APP_ASSETS" "$PREVIEW_ASSETS"

if command -v rsync >/dev/null 2>&1; then
    rsync -a \
      --exclude='*.php' \
      --exclude='*.phtml' \
      --exclude='*.phar' \
      --exclude='*.htaccess' \
      --exclude='.env*' \
      --exclude='*.sql' \
      --exclude='*.zip' \
      --exclude='*.tar' \
      --exclude='*.gz' \
      "$OLD/" "$APP_ASSETS/"
    rsync -a "$APP_ASSETS/" "$PREVIEW_ASSETS/"
else
    python3 - <<'PY'
from pathlib import Path
import shutil

src = Path("/home/cghggujarat/public_html/website")
dst1 = Path("/home/cghggujarat/laravel_apps/cghg_portal/public/assets/website-legacy")
dst2 = Path("/home/cghggujarat/public_html/new/portalarea-laravel-preview/assets/website-legacy")

blocked_suffixes = {".php",".phtml",".phar",".sql",".zip",".tar",".gz"}
blocked_names = {".htaccess",".env"}

for p in src.rglob("*"):
    if not p.is_file():
        continue
    if p.suffix.lower() in blocked_suffixes:
        continue
    if p.name in blocked_names or p.name.startswith(".env"):
        continue

    rel = p.relative_to(src)
    for root in (dst1,dst2):
        target = root / rel
        target.parent.mkdir(parents=True, exist_ok=True)
        shutil.copy2(p,target)
PY
fi

chown -R "$OWNER" "$APP_ASSETS" "$PREVIEW_ASSETS" 2>/dev/null || true
find "$APP_ASSETS" "$PREVIEW_ASSETS" -type d -exec chmod 755 {} \;
find "$APP_ASSETS" "$PREVIEW_ASSETS" -type f -exec chmod 644 {} \;

echo "STATIC_ASSETS_APP=$(find "$APP_ASSETS" -type f | wc -l)"
echo "STATIC_ASSETS_PREVIEW=$(find "$PREVIEW_ASSETS" -type f | wc -l)"

say "4/9 RENDER OLD WEBSITE SOURCE"

RAW="$BACKUP/old-rendered.html"

if curl -LfsS --max-time 30 "https://cghggujarat.in/website/" -o "$RAW" && [ -s "$RAW" ]; then
    echo "SOURCE=LIVE_RENDERED_HTML"
else
    echo "Live self-request unavailable; using local source fallback."
    case "$OLD_INDEX" in
        *.php)
            (
                cd "$OLD"
                "$PHP82" "$(basename "$OLD_INDEX")"
            ) > "$RAW" 2>"$BACKUP/old-render.stderr" || true
            ;;
        *)
            cp -a "$OLD_INDEX" "$RAW"
            ;;
    esac
fi

[ -s "$RAW" ] || fail "Could not render/read old website"
echo "RENDERED_BYTES=$(wc -c < "$RAW")"

say "5/9 CONVERT OLD WEBSITE HTML TO LARAVEL BLADE"

export RAW
python3 - <<'PY'
from pathlib import Path
import os, re

raw = Path(os.environ["RAW"])
text = raw.read_text(errors="replace")

base_tag = "<base href=\"https://cghggujarat.in/website/\">"
font_patch = (
    "<link rel=\"preconnect\" href=\"https://fonts.googleapis.com\">\n"
    "<link rel=\"preconnect\" href=\"https://fonts.gstatic.com\" crossorigin>\n"
    "<link href=\"https://fonts.googleapis.com/css2?family=Anek+Gujarati:wght@400;500;600;700;800&display=swap\" rel=\"stylesheet\">\n"
    "<style id=\"cghg-laravel-font-bridge\">\n"
    ":lang(gu), [lang=\"gu\"], .gujarati, .guj {font-family:\"Anek Gujarati\",sans-serif !important;}\n"
    "</style>"
)

if re.search(r"</head\s*>", text, flags=re.I):
    text = re.sub(
        r"</head\s*>",
        base_tag + "\n" + font_patch + "\n</head>",
        text,
        count=1,
        flags=re.I
    )
else:
    text = base_tag + "\n" + font_patch + "\n" + text

# Keep original old-site links/assets unchanged for exact visual fidelity in preview.
# Static assets are also copied locally above for the later final cut-over.
# Patch the old "Login Portal" anchor to the current Laravel officer login.
anchor_re = re.compile(
    r'(<a\b[^>]*\bhref\s*=\s*)(["\'])(.*?)(\2)([^>]*>\s*(?:<[^>]+>\s*)*Login\s*Portal(?:\s*</[^>]+>)*\s*</a>)',
    re.I | re.S
)

def login_repl(m):
    return m.group(1) + m.group(2) + "{{ route('login') }}" + m.group(4) + m.group(5)

text, login_count = anchor_re.subn(login_repl, text)

text = re.sub(
    r'href=(["\'])(?:\.\./)?portalarea/login/index\.php\1',
    'href="{{ route(\'login\') }}"',
    text,
    flags=re.I
)

text = "<!-- CGHG_OLD_WEBSITE_EXACT_LAYOUT_V9 -->\n" + text

out = Path("/home/cghggujarat/laravel_apps/cghg_portal/resources/views/website/home.blade.php")
out.write_text(text)

print(f"BLADE_BYTES={out.stat().st_size}")
print(f"LOGIN_TEXT_PATCHES={login_count}")
PY

say "6/9 FORCE /website TO RENDER EXACT OLD LAYOUT"

python3 - <<'PY'
from pathlib import Path
import re

p = Path("/home/cghggujarat/laravel_apps/cghg_portal/routes/web.php")
s = p.read_text()

replacement = "Route::view('/website', 'website.home')->name('website.home');"

patterns = [
    r"Route::view\(\s*['\"]/website/?['\"]\s*,\s*['\"][^'\"]+['\"]\s*\)\s*->name\(\s*['\"]website\.home['\"]\s*\)\s*;",
    r"Route::get\(\s*['\"]/website/?['\"]\s*,\s*function\s*\([^)]*\)\s*\{.*?\}\s*\)\s*->name\(\s*['\"]website\.home['\"]\s*\)\s*;",
    r"Route::get\(\s*['\"]/website/?['\"]\s*,\s*fn\s*\([^)]*\)\s*=>.*?\)\s*->name\(\s*['\"]website\.home['\"]\s*\)\s*;",
]

changed = False
for pat in patterns:
    ns, count = re.subn(pat, replacement, s, count=1, flags=re.S)
    if count:
        s = ns
        changed = True
        break

if not changed:
    if "->name('website.home')" not in s and '->name("website.home")' not in s:
        block = "\n// CGHG_OLD_WEBSITE_EXACT_V9\n" + replacement + "\n"
        if "?>" in s:
            s = s.replace("?>", block + "?>", 1)
        else:
            s += block
        changed = True

p.write_text(s)
print("ROUTE_PATCHED=" + ("YES" if changed else "EXISTING_NAMED_ROUTE_PRESERVED"))
PY

say "7/9 OWNERSHIP + SYNTAX"
chown -R "$OWNER" resources/views/website "$APP/public/assets/website-legacy" "$PREVIEW/assets/website-legacy" routes/web.php 2>/dev/null || true
chmod 644 resources/views/website/home.blade.php routes/web.php

"$PHP82" -l routes/web.php

say "8/9 LARAVEL CACHE + ROUTE CHECK"
runuser -u cghggujarat -- env HOME=/home/cghggujarat "$PHP82" artisan optimize:clear
runuser -u cghggujarat -- env HOME=/home/cghggujarat "$PHP82" artisan view:cache
runuser -u cghggujarat -- env HOME=/home/cghggujarat "$PHP82" artisan route:list --path=website | head -80

say "9/9 VERIFY"
grep -q "CGHG_OLD_WEBSITE_EXACT_LAYOUT_V9" resources/views/website/home.blade.php
grep -q "Welcome" resources/views/website/home.blade.php
grep -q "Our Mission" resources/views/website/home.blade.php
grep -q "Privacy Policy" resources/views/website/home.blade.php
grep -q "Data Deletion" resources/views/website/home.blade.php

echo "OLD_LAYOUT_SOURCE=OK"
echo "OLD_CONTENT_ORDER=UNCHANGED"
echo "OLD_STATIC_ASSETS=COPIED_FOR_FINAL_CUTOVER"
echo "ANEK_GUJARATI=ADDED_WITHOUT_LAYOUT_CHANGE"
echo "LARAVEL_OFFICER_LOGIN=CONNECTED"
echo "CURRENT_OFFICER_AUTH_DASHBOARDS=UNTOUCHED"
echo
echo "PREVIEW=https://cghggujarat.in/new/portalarea-laravel-preview/website"
echo "BACKUP=$BACKUP"
echo "ROLLBACK=bash $BACKUP/ROLLBACK.sh"
echo
echo "============================================================"
echo "CGHG OLD WEBSITE EXACT LAYOUT V9 INSTALLED"
echo "============================================================"
