#!/bin/bash
# StorePilot server helper for cPanel Terminal.
#
#   bash storepilot.sh exposed     Test from the internet whether .env (and other private files) can be downloaded.
#   bash storepilot.sh secure      ONE TIME: move the backend (with .env, code, database settings, uploads)
#                                  out of the website into ~/storepilot-app. Web addresses stay the same.
#   bash storepilot.sh undo-secure Put the backend back where it was (only if "secure" caused a problem).
#
#   bash storepilot.sh before      Back up, then show the "updating" page.   (run BEFORE uploading an update)
#   bash storepilot.sh after       Update database, caches, permissions, security check, back online.
#                                                                          (run AFTER uploading an update)
#   bash storepilot.sh backup      Database + files backup (any time).
#   bash storepilot.sh check       Security check (any time).
#
# Defaults: website folder ~/public_html/StorePilot. If yours is elsewhere, first run e.g.
#   export STOREPILOT_WEB=~/mydomain.com/StorePilot
# A second StorePilot in the same cPanel account also needs its own safe folder, e.g.
#   export STOREPILOT_SAFE=~/storepilot-app-shop2

set -uo pipefail

WEB="${STOREPILOT_WEB:-$HOME/provision.therismosagribusiness.org/StorePilot}"
SAFE="${STOREPILOT_SAFE:-$HOME/storepilot-app-provision}"
# Each copy keeps its own backups: ~/storepilot-app -> ~/storepilot-backups, ~/storepilot-app-shop2 -> ~/storepilot-backups-shop2
BACKUPS="${STOREPILOT_BACKUPS:-$(dirname "$SAFE")/$(basename "$SAFE" | sed 's/storepilot-app/storepilot-backups/')}"
STAMP="$(date +%Y%m%d-%H%M%S)"
PHP="${PHP_BIN:-php}"

say()  { printf '\n\033[1m== %s\033[0m\n' "$1"; }
fail() { printf '\n\033[31mSTOPPED: %s\033[0m\n' "$1"; exit 1; }

# Where the backend is now: moved out of the website (safe) or still inside it
if [ -n "${STOREPILOT_DIR:-}" ]; then APP="$STOREPILOT_DIR"
elif [ -f "$SAFE/artisan" ]; then APP="$SAFE"
else APP="$WEB/backend"; fi
WEBPUB="$WEB/backend/public"
MOVED=0; [ "$APP" != "$WEB/backend" ] && MOVED=1

need_app() {
    [ -f "$APP/artisan" ] || fail "No StorePilot backend found at $APP. Set STOREPILOT_WEB to the folder that holds 'backend' and 'frontend'."
    [ -f "$APP/.env" ]    || fail "$APP/.env is missing."
    cd "$APP" || fail "Cannot open $APP"
}

site_url() {
    # The site address from APP_URL in .env (e.g. https://shop.com/StorePilot/backend/public -> https://shop.com)
    grep -E '^APP_URL=' "$APP/.env" | cut -d= -f2- | tr -d '"\r' | sed -E 's#^(https?://[^/]+).*#\1#'
}

backup() {
    need_app
    mkdir -p "$BACKUPS" && chmod 700 "$BACKUPS"

    say "Backing up the database"
    if "$PHP" artisan backup:database --keep=30 >/dev/null 2>&1 && LATEST=$(ls -t storage/app/backups/*.sql 2>/dev/null | head -1) && [ -s "$LATEST" ]; then
        cp -p "$LATEST" "$BACKUPS/db-$STAMP.sql"
    else
        DB_NAME=$(grep -E '^DB_DATABASE=' .env | cut -d= -f2- | tr -d '"\r')
        DB_USER=$(grep -E '^DB_USERNAME=' .env | cut -d= -f2- | tr -d '"\r')
        DB_PASS=$(grep -E '^DB_PASSWORD=' .env | cut -d= -f2- | tr -d '"\r')
        MYSQL_PWD="$DB_PASS" mysqldump -u "$DB_USER" --single-transaction --routines "$DB_NAME" > "$BACKUPS/db-$STAMP.sql" \
            || fail "Database backup failed. Nothing was changed. Export it in phpMyAdmin instead, then run again."
    fi
    [ -s "$BACKUPS/db-$STAMP.sql" ] || fail "The database backup is empty. Nothing was changed."
    gzip -f "$BACKUPS/db-$STAMP.sql"
    echo "Database saved: $BACKUPS/db-$STAMP.sql.gz"

    say "Backing up the app files (.env and uploaded pictures included, vendor left out)"
    tar -czf "$BACKUPS/files-$STAMP.tar.gz" --exclude=./vendor --exclude=./storage/app/backups \
        --exclude=./storage/framework --exclude=./storage/logs -C "$APP" . \
        || fail "File backup failed. Nothing was changed."
    echo "Files saved:    $BACKUPS/files-$STAMP.tar.gz"
    chmod 600 "$BACKUPS"/* 2>/dev/null
    ls -t "$BACKUPS"/db-*.sql.gz 2>/dev/null | tail -n +11 | xargs -r rm -f
    ls -t "$BACKUPS"/files-*.tar.gz 2>/dev/null | tail -n +11 | xargs -r rm -f
}

# The website's entry file: loads the app from its safe folder, outside the website
write_entry() {
    cat > "$WEBPUB/index.php" <<PHP
<?php
// StorePilot web entry. The app itself (code, .env, uploads) lives outside the website in:
\$appDir = '$SAFE';

use Illuminate\\Http\\Request;

define('LARAVEL_START', microtime(true));

if (file_exists(\$maintenance = \$appDir.'/storage/framework/maintenance.php')) {
    require \$maintenance;
}

require \$appDir.'/vendor/autoload.php';

\$app = require_once \$appDir.'/bootstrap/app.php';
\$app->usePublicPath(__DIR__);

\$app->handleRequest(Request::capture());
PHP
    chmod 644 "$WEBPUB/index.php"
}

# Keeps the web folder's small files (.htaccess, robots) in step with the app's copy
sync_web_public() {
    [ "$MOVED" = 1 ] || return 0
    mkdir -p "$WEBPUB"
    for f in .htaccess robots.txt favicon.ico; do
        [ -f "$APP/public/$f" ] && cp -p "$APP/public/$f" "$WEBPUB/$f"
    done
    [ -f "$APP/.htaccess" ] && cp -p "$APP/.htaccess" "$WEB/backend/.htaccess"
    if ! grep -qsF "$SAFE" "$WEBPUB/index.php"; then write_entry; fi
    [ -L "$WEBPUB/storage" ] || { rm -rf "$WEBPUB/storage"; ln -s "$APP/storage/app/public" "$WEBPUB/storage"; }
}

rebuild() {
    rm -f bootstrap/cache/packages.php bootstrap/cache/services.php bootstrap/cache/config.php bootstrap/cache/routes-v7.php bootstrap/cache/events.php
    "$PHP" artisan optimize:clear >/dev/null
    "$PHP" artisan optimize || fail "Rebuilding caches failed. Send the error above."
}

permissions() {
    say "Setting safe permissions"
    find "$APP" -path "$APP/vendor" -prune -o -type d -exec chmod 755 {} +
    find "$APP" -path "$APP/vendor" -prune -o -type f -exec chmod 644 {} +
    chmod 600 "$APP/.env"
    chmod 755 "$APP/artisan"
}

exposed() {
    need_app
    URL=$(site_url)
    [ -n "$URL" ] || fail "APP_URL is not set in .env, so the site address is unknown."
    # The StorePilot folder's web address: APP_URL without /backend/public
    BASEURL=$(grep -E '^APP_URL=' "$APP/.env" | cut -d= -f2- | tr -d '"\r' | sed -E 's#/+$##; s#/backend/public$##')
    REL="${BASEURL#$URL}"
    say "Testing $URL$REL from the internet (200 = can be downloaded = BAD)"
    for p in backend/.env backend/composer.json backend/storage/logs/laravel.log backend/artisan backend/config/database.php frontend/package.json; do
        code=$(curl -s -o /dev/null -w '%{http_code}' "$URL$REL/$p")
        if [ "$code" = "200" ]; then flag="EXPOSED"; else flag="ok"; fi
        printf '  %-40s %s  %s\n' "$p" "$code" "$flag"
    done
    code=$(curl -s -o /dev/null -w '%{http_code}' "$URL$REL/backend/public/up")
    printf '  %-40s %s  %s\n' "backend/public/up (should be 200)" "$code" "$([ "$code" = 200 ] && echo ok || echo CHECK)"
}

check() {
    need_app
    say "Security check"
    "$PHP" artisan security:check || true

    say ".env essentials"
    for key in APP_ENV APP_DEBUG APP_URL FRONTEND_URL SESSION_SECURE_COOKIE; do
        printf '  %-22s %s\n' "$key" "$(grep -E "^$key=" .env | cut -d= -f2- || echo '(not set)')"
    done
    if grep -qE '^APP_DEBUG=true' .env; then echo "  !! APP_DEBUG must be false on a live server"; fi
    if ! grep -qE '^APP_ENV=production' .env; then echo "  !! APP_ENV should be production"; fi
    RK=$(grep -E '^RECOVERY_KEY=' .env | cut -d= -f2- | tr -d '"\r')
    if [ "${#RK}" -lt 16 ]; then echo "  !! RECOVERY_KEY is shorter than 16 characters: password recovery stays off"; fi
    if [ "$MOVED" = 1 ]; then echo "  OK  The backend lives outside the website ($APP)"
    else echo "  !! The backend (with .env) is inside the website. Run: bash storepilot.sh secure"; fi
}

case "${1:-}" in
    exposed) exposed ;;

    secure)
        [ "$MOVED" = 0 ] || fail "Already done: the backend is in $APP, outside the website."
        [ -e "$SAFE" ] && fail "$SAFE already exists. Rename or remove it first."
        [ -d "$WEB/frontend" ] || fail "No $WEB/frontend folder. Set STOREPILOT_WEB to the folder that holds 'backend' and 'frontend'."
        backup
        say "Showing the 'updating' page"
        "$PHP" artisan down --retry=30 >/dev/null 2>&1 || true

        say "Moving the backend out of the website"
        cd "$HOME"
        mv "$WEB/backend" "$SAFE" || fail "Could not move the folder. Nothing was changed."
        APP="$SAFE"; MOVED=1; cd "$APP"
        rm -f "$APP/public/storage"

        say "Leaving only the web entry in the website"
        mkdir -p "$WEBPUB"
        write_entry
        sync_web_public

        rebuild
        permissions
        "$PHP" artisan up
        sleep 2
        exposed
        echo
        echo "Done. Web addresses are unchanged. If anything looks wrong: bash storepilot.sh undo-secure"
        ;;

    undo-secure)
        [ "$MOVED" = 1 ] || fail "Nothing to undo: the backend is still inside the website."
        [ -d "$WEB/backend" ] && mv "$WEB/backend" "$WEB/backend-web-$STAMP"
        mv "$SAFE" "$WEB/backend" || fail "Could not move the folder back."
        APP="$WEB/backend"; MOVED=0; cd "$APP"
        rebuild
        [ -e public/storage ] || "$PHP" artisan storage:link
        "$PHP" artisan up
        echo "Back to the old layout. The small web folder was kept as $WEB/backend-web-$STAMP (you can delete it)."
        ;;

    before)
        backup
        say "Showing the 'updating' page"
        "$PHP" artisan down --retry=60 || true
        echo
        echo "Now upload and extract the new files, then run:  bash storepilot.sh after"
        ;;

    after)
        need_app
        say "Updating the database"
        "$PHP" artisan migrate --force || fail "The database update failed. The app stays on the 'updating' page. Send the error above."
        sync_web_public
        if [ "$MOVED" = 0 ] && [ ! -e public/storage ]; then "$PHP" artisan storage:link; fi
        say "Rebuilding caches"
        rebuild
        permissions
        check
        say "Back online"
        "$PHP" artisan up
        echo
        echo "Done. Open the app, sign in, and make one test sale."
        ;;

    backup) backup ;;
    check)  check ;;
    *)
        echo "Usage: bash storepilot.sh exposed | secure | undo-secure | before | after | backup | check"
        exit 1
        ;;
esac
