#!/usr/bin/env bash
# rsync_deploy — Sincroniza un directorio local a un host remoto via rsync+SSH
set -euo pipefail

rsync_deploy() {
    local local_dir="$1"
    local ssh_alias="$2"
    local remote_dir="$3"

    if [[ -z "$local_dir" || -z "$ssh_alias" || -z "$remote_dir" ]]; then
        echo "rsync_deploy: se requieren local_dir, ssh_alias y remote_dir" >&2
        return 1
    fi

    if [[ ! -d "$local_dir" ]]; then
        echo "rsync_deploy: directorio local '$local_dir' no existe" >&2
        return 1
    fi

    # Crear directorio remoto si no existe
    echo "rsync_deploy: verificando directorio remoto '$remote_dir' en '$ssh_alias'..." >&2
    if ! ssh "$ssh_alias" "mkdir -p '$remote_dir'" 2>&1; then
        echo "rsync_deploy: no se pudo crear el directorio remoto '$remote_dir' en '$ssh_alias'" >&2
        return 1
    fi

    # Ejecutar rsync y capturar salida para parsear estadísticas
    local rsync_output
    rsync_output=$(rsync -avz --delete \
        --exclude='.git' \
        --exclude='operations.db*' \
        --exclude='*.exe' \
        --exclude='node_modules' \
        --exclude='.venv' \
        --exclude='__pycache__' \
        --exclude='build/' \
        --exclude='*.db-shm' \
        --exclude='*.db-wal' \
        -e ssh \
        "$local_dir" \
        "${ssh_alias}:${remote_dir}" 2>&1) || {
        echo "rsync_deploy: rsync falló al sincronizar '$local_dir' → '${ssh_alias}:${remote_dir}'" >&2
        echo "$rsync_output" >&2
        return 1
    }

    echo "$rsync_output" >&2

    # Parsear número de archivos transferidos
    local files_transferred
    files_transferred=$(echo "$rsync_output" | grep -oP 'Number of regular files transferred: \K[0-9,]+' | tr -d ',' || echo "0")
    if [[ -z "$files_transferred" ]]; then
        # Intentar formato alternativo de rsync
        files_transferred=$(echo "$rsync_output" | grep -oP 'Number of files transferred: \K[0-9,]+' | tr -d ',' || echo "0")
    fi
    if [[ -z "$files_transferred" ]]; then
        files_transferred="0"
    fi

    # Parsear tamaño total transferido
    local total_size
    total_size=$(echo "$rsync_output" | grep -oP 'Total transferred file size: \K[0-9,.]+ \w+' || echo "0 bytes")
    if [[ -z "$total_size" ]]; then
        total_size="0 bytes"
    fi

    # Emitir JSON a stdout
    printf '{"files_transferred": %s, "total_size": "%s", "ssh_alias": "%s", "remote_dir": "%s"}\n' \
        "$files_transferred" \
        "$total_size" \
        "$ssh_alias" \
        "$remote_dir"
}

if [[ "${BASH_SOURCE[0]}" == "$0" ]]; then
    rsync_deploy "$@"
fi
