#!/usr/bin/env bash
# onx-wp-staging-clone — WordPress staging kopyalama (rsync + DB dump/import + URL replace).
#
# Input (stdin JSON) — action="clone" (varsayılan) veya "db-clone" veya "delete":
#
#  Dosya klonlama (action=clone, varsayılan):
#   {
#     "action":           "clone",
#     "source_path":      "/home/onx_xxx/public_html",
#     "target_path":      "/home/onx_xxx/staging",
#     "username":         "onx_xxx",
#     "exclude":          ["wp-content/cache", "wp-content/uploads/cache"],
#     "staging_app_id":   42,
#     "production_app_id": 10
#   }
#
#  DB klonlama (action=db-clone):
#   {
#     "action":           "db-clone",
#     "source_db":        "onx_xxx_wp10",
#     "target_db":        "onx_xxx_wp10_staging",
#     "source_url":       "https://site.com",
#     "staging_url":      "https://staging.site.com",
#     "wp_path":          "/home/onx_xxx/staging",
#     "username":         "onx_xxx"
#   }
#
#  Silme (action=delete):
#   {
#     "action":  "delete",
#     "wp_path": "/home/onx_xxx/staging",
#     "db_name": "onx_xxx_wp10_staging",
#     "username": "onx_xxx"
#   }
#
# Output (stdout JSON):
#   {"success":true, "action":"clone", "files_count":N, "duration_ms":N}
#
# Exit codes: 0=ok  1=invalid-input  2=preflight-fail  3=exec-fail  4=rollback-ok  5=rollback-fail
#
# Deployed to: /usr/local/onoxsoft/bin/onx-wp-staging-clone

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=_lib/common.sh
source "${SCRIPT_DIR}/_lib/common.sh"

WP_CLI_BIN="${WP_CLI_BIN:-/usr/local/bin/wp}"

require_root
require_cmd rsync
require_cmd mysql
require_cmd mysqldump

onx_json_input

ACTION="$(onx_json_field action 'clone')"
USERNAME="$(onx_json_field username)"

[[ -z "$USERNAME" ]] && onx_die 1 "username zorunlu"
onx_validate_username "$USERNAME"

START_NS=$(date +%s%N)

# ─── Action: clone (rsync dosyalar) ──────────────────────────────────────────
if [[ "$ACTION" == "clone" ]]; then
    SOURCE_PATH="$(onx_json_field source_path)"
    TARGET_PATH="$(onx_json_field target_path)"

    [[ -z "$SOURCE_PATH" ]] && onx_die 1 "source_path zorunlu"
    [[ -z "$TARGET_PATH" ]] && onx_die 1 "target_path zorunlu"
    [[ -d "$SOURCE_PATH" ]] || onx_die 2 "source_path mevcut değil: '${SOURCE_PATH}'"

    # exclude listesi
    RSYNC_EXCLUDES=()
    while IFS= read -r ex; do
        [[ -n "$ex" ]] && RSYNC_EXCLUDES+=("--exclude=${ex}")
    done < <(echo "$INPUT" | jq -r '.exclude // [] | .[]')

    # Varsayılan exclude'lar
    RSYNC_EXCLUDES+=(
        "--exclude=wp-content/cache"
        "--exclude=wp-content/uploads/cache"
        "--exclude=*.log"
        "--exclude=.git"
    )

    onx_log "staging-clone: ${SOURCE_PATH} → ${TARGET_PATH} (user=${USERNAME})"

    # Target dizini oluştur
    mkdir -p "$TARGET_PATH"
    chown "${USERNAME}:${USERNAME}" "$TARGET_PATH"
    onx_rollback_register "rm -rf '${TARGET_PATH}'"
    trap 'onx_rollback_run' ERR

    rsync -a --delete \
        "${RSYNC_EXCLUDES[@]}" \
        "${SOURCE_PATH}/" \
        "${TARGET_PATH}/" \
        --chown="${USERNAME}:${USERNAME}"

    # Dosya sayısını hesapla
    FILES_COUNT=$(find "$TARGET_PATH" -type f 2>/dev/null | wc -l || echo 0)

    END_NS=$(date +%s%N)
    DURATION_MS=$(( (END_NS - START_NS) / 1000000 ))

    onx_json_out action clone success true files_count "$FILES_COUNT" duration_ms "$DURATION_MS"

# ─── Action: db-clone (mysqldump + import + search-replace) ──────────────────
elif [[ "$ACTION" == "db-clone" ]]; then
    SOURCE_DB="$(onx_json_field source_db)"
    TARGET_DB="$(onx_json_field target_db)"
    SOURCE_URL="$(onx_json_field source_url)"
    STAGING_URL="$(onx_json_field staging_url)"
    WP_PATH="$(onx_json_field wp_path)"

    [[ -z "$SOURCE_DB"   ]] && onx_die 1 "source_db zorunlu"
    [[ -z "$TARGET_DB"   ]] && onx_die 1 "target_db zorunlu"
    [[ -z "$SOURCE_URL"  ]] && onx_die 1 "source_url zorunlu"
    [[ -z "$STAGING_URL" ]] && onx_die 1 "staging_url zorunlu"
    [[ -z "$WP_PATH"     ]] && onx_die 1 "wp_path zorunlu"

    # DB adı güvenlik
    [[ "$SOURCE_DB" =~ ^onx_[a-z0-9]+_[a-z0-9_]+$ ]] || onx_die 1 "Geçersiz source_db: '${SOURCE_DB}'"
    [[ "$TARGET_DB" =~ ^onx_[a-z0-9]+_[a-z0-9_]+$ ]] || onx_die 1 "Geçersiz target_db: '${TARGET_DB}'"

    DUMP_FILE="/tmp/onx-staging-${TARGET_DB}-$(date +%s).sql"

    onx_log "staging-db-clone: ${SOURCE_DB} → ${TARGET_DB}"
    onx_rollback_register "mysql -e 'DROP DATABASE IF EXISTS \`${TARGET_DB}\`;'"
    onx_rollback_register "rm -f '${DUMP_FILE}'"
    trap 'onx_rollback_run' ERR

    # 1. DB dump
    mysqldump --single-transaction --routines --triggers "$SOURCE_DB" > "$DUMP_FILE" \
        || onx_die 3 "mysqldump başarısız: ${SOURCE_DB}"

    # 2. Target DB oluştur
    mysql -e "CREATE DATABASE IF NOT EXISTS \`${TARGET_DB}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;" \
        || onx_die 3 "CREATE DATABASE başarısız: ${TARGET_DB}"

    # 3. Import
    mysql "$TARGET_DB" < "$DUMP_FILE" \
        || onx_die 3 "DB import başarısız: ${TARGET_DB}"

    rm -f "$DUMP_FILE"

    # 4. URL search-replace (WP-CLI gerektirir)
    if command -v "$WP_CLI_BIN" >/dev/null 2>&1 && [[ -f "${WP_PATH}/wp-config.php" ]]; then
        sudo -u "$USERNAME" "$WP_CLI_BIN" \
            --path="$WP_PATH" \
            --no-color \
            search-replace "$SOURCE_URL" "$STAGING_URL" \
            --all-tables \
            2>&1 | onx_log "search-replace output: $(cat)" || true

        # Staging'i no-index yap
        sudo -u "$USERNAME" "$WP_CLI_BIN" \
            --path="$WP_PATH" \
            --no-color \
            option update blog_public 0 || true
    fi

    END_NS=$(date +%s%N)
    DURATION_MS=$(( (END_NS - START_NS) / 1000000 ))

    onx_json_out action db-clone success true source_db "$SOURCE_DB" target_db "$TARGET_DB" duration_ms "$DURATION_MS"

# ─── Action: delete (staging'i kaldır) ────────────────────────────────────────
elif [[ "$ACTION" == "delete" ]]; then
    WP_PATH="$(onx_json_field wp_path)"
    DB_NAME="$(onx_json_field db_name)"

    [[ -z "$WP_PATH" ]] && onx_die 1 "wp_path zorunlu"

    # Güvenlik: sadece /home/<user>/ altı silinebilir
    [[ "$WP_PATH" =~ ^/home/[a-zA-Z0-9_]+ ]] || onx_die 1 "wp_path güvenli değil: '${WP_PATH}'"

    onx_log "staging-delete: path=${WP_PATH} db=${DB_NAME:-none}"

    if [[ -n "$DB_NAME" ]]; then
        [[ "$DB_NAME" =~ ^onx_[a-z0-9]+_[a-z0-9_]+$ ]] || onx_die 1 "Geçersiz db_name"
        mysql -e "DROP DATABASE IF EXISTS \`${DB_NAME}\`;" \
            || onx_log "UYARI: DB drop başarısız: ${DB_NAME}"
    fi

    if [[ -d "$WP_PATH" ]]; then
        rm -rf "$WP_PATH"
    fi

    END_NS=$(date +%s%N)
    DURATION_MS=$(( (END_NS - START_NS) / 1000000 ))

    onx_json_out action delete success true duration_ms "$DURATION_MS"

else
    onx_die 1 "Bilinmeyen action: '${ACTION}'. Beklenenler: clone, db-clone, delete"
fi
