#!/usr/bin/env bash
# docker_compose_remote_deploy — Despliega un stack Docker Compose en un host remoto via SSH
set -euo pipefail

docker_compose_remote_deploy() {
    local host="$1"
    local remote_dir="$2"
    local branch="${3:-main}"
    local compose_files="${4:-}"

    if [[ -z "$host" || -z "$remote_dir" ]]; then
        echo "docker_compose_remote_deploy: se requieren host y remote_dir" >&2
        return 1
    fi

    local start_ts
    start_ts=$(date +%s)

    # 1. Verificar conectividad SSH
    echo "docker_compose_remote_deploy: verificando conectividad SSH a '$host'..." >&2
    if ! ssh -o BatchMode=yes -o ConnectTimeout=5 "$host" true 2>/dev/null; then
        echo "docker_compose_remote_deploy: no se puede conectar a '$host' via SSH" >&2
        return 1
    fi

    # 2. Git pull en el host remoto
    echo "docker_compose_remote_deploy: git pull origin $branch en '$remote_dir'..." >&2
    if ! ssh "$host" "cd '$remote_dir' && git pull origin '$branch'" >&2; then
        echo "docker_compose_remote_deploy: git pull falló en '$host:$remote_dir'" >&2
        return 1
    fi

    # 3. Construir los argumentos -f para docker-compose
    local compose_args="-f docker-compose.yml"
    if [[ -n "$compose_files" ]]; then
        local IFS=","
        local extra_file
        for extra_file in $compose_files; do
            extra_file="${extra_file// /}"  # trim spaces
            if [[ -n "$extra_file" ]]; then
                compose_args="$compose_args -f $extra_file"
            fi
        done
        unset IFS
    fi

    # 4. docker-compose pull
    echo "docker_compose_remote_deploy: actualizando imagenes ($compose_args)..." >&2
    if ! ssh "$host" "cd '$remote_dir' && docker-compose $compose_args pull" >&2; then
        echo "docker_compose_remote_deploy: docker-compose pull falló en '$host:$remote_dir'" >&2
        return 1
    fi

    # 5. docker-compose up -d
    echo "docker_compose_remote_deploy: levantando servicios ($compose_args)..." >&2
    if ! ssh "$host" "cd '$remote_dir' && docker-compose $compose_args up -d" >&2; then
        echo "docker_compose_remote_deploy: docker-compose up -d falló en '$host:$remote_dir'" >&2
        return 1
    fi

    # 6. Recopilar containers corriendo tras el deploy
    local containers_json
    containers_json=$(ssh "$host" \
        "docker ps --format '{{.Names}}' 2>/dev/null | jq -R . | jq -sc ." 2>/dev/null || echo '[]')

    local end_ts
    end_ts=$(date +%s)
    local duration_ms=$(( (end_ts - start_ts) * 1000 ))

    # Emitir JSON a stdout
    printf '{"status":"ok","host":"%s","remote_dir":"%s","branch":"%s","containers":%s,"duration_ms":%d}\n' \
        "$host" \
        "$remote_dir" \
        "$branch" \
        "$containers_json" \
        "$duration_ms"
}

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