#!/usr/bin/env bash
# 실행 중인 컨테이너 엔진(Colima · Kiri · Podman · Docker Desktop)을 같은 docker CLI 로 측정해 results.json 을 만든다.
# 엔진을 켜거나 끄지 않는다. 응답하지 않는 엔진은 건너뛴다.
# 필요: docker CLI, hyperfine, jq, curl, rg (macOS 기준: footprint, lsof, top)
set -euo pipefail
cd "$(dirname "$0")"

RUNS=${RUNS:-20}    # run · exec 반복 횟수
PINGS=${PINGS:-100} # API _ping 반복 횟수
REPS=${REPS:-3}     # 파일 I/O 반복 횟수 (중앙값 사용)
FILE_MB=${FILE_MB:-256}
SMALL_FILES=${SMALL_FILES:-5000}
IMAGE=alpine:3
OUT=${OUT:-results.json}

# 바인드 마운트 대상은 모든 VM 이 기본으로 공유하는 $HOME 아래에 둔다 (/var/folders 는 colima 가 공유하지 않음)
mkdir -p "$HOME/.cache"
WORK=$(mktemp -d "$HOME/.cache/crt-bench.XXXXXX")
trap 'rm -rf "$WORK"' EXIT

podman_sock=$(podman machine inspect --format '{{.ConnectionInfo.PodmanSocket.Path}}' 2>/dev/null || true)

# id|표시 이름|소켓|VM 프로세스가 연 디스크 이미지 경로(정규식)|엔진 호스트 프로세스(pgrep -f, 쉼표 구분)
ENGINES=(
    "docker-desktop|Docker Desktop|$HOME/.docker/run/docker.sock|Docker\.raw|com.docker.backend,com.docker.virtualization,com.docker.krun"
    "podman|Podman|$podman_sock|containers/podman/machine/|vfkit,krunkit,gvproxy"
    "colima|Colima|$HOME/.config/colima/default/docker.sock|_lima/(_disks/)?colima/|colima daemon,limactl hostagent,limactl usernet"
    "kiri|Kiri|$HOME/.kiri/run/docker.sock|Kiri/vm/|kiri daemon"
)

log() { printf '\033[2m%s\033[0m\n' "$*" >&2; }

# 숫자(한 줄에 하나) → {median, p90, min, max}
stats() {
    jq -s 'sort | {
		median: (if length % 2 == 1 then .[length / 2 | floor] else (.[length / 2 - 1] + .[length / 2]) / 2 end),
		p90: .[(length * 0.9 | ceil) - 1], min: .[0], max: .[-1], n: length
	} | map_values(if type == "number" then (. * 100 | round / 100) else . end)'
}
median() { stats | jq '.median'; }

# hyperfine 실행 후 ms 단위 통계
hf() {
    local runs=$1 warm=$2
    shift 2
    hyperfine -N --style none --runs "$runs" --warmup "$warm" --export-json "$WORK/hf.json" "$@" >/dev/null 2>&1
    jq '.results[0] | (.times // [.measurements[].time_wall_clock.value])[] * 1000' "$WORK/hf.json" | stats
}

# 해당 엔진의 디스크 이미지를 연 Virtualization.framework VM 프로세스
# (VM 프로세스는 모두 launchd 자식이라 부모 · 시작 시각으로는 엔진을 확실히 가를 수 없다)
vm_pid_by_disk() {
    local pat=$1 p
    for p in $(pgrep -f 'com.apple.Virtualization.VirtualMachine' || true); do
        if lsof -p "$p" 2>/dev/null | rg -q "$pat"; then
            echo "$p"
            return
        fi
    done
}

footprint_mb() {
    footprint -p "$1" 2>/dev/null | sed -n 's/.*Footprint: \([0-9.]*\) \([KMG]B\).*/\1 \2/p' | head -1 |
        awk '{ v = $1; if ($2 == "KB") v /= 1024; if ($2 == "GB") v *= 1024; printf "%.1f", v }'
}

# 측정 중 VM·엔진 프로세스 CPU(%) — top 2회 샘플 중 두 번째 값
cpu_pct() {
    top -l 2 -s 3 -pid "$1" -stats cpu 2>/dev/null | awk 'NF == 1 && $1 ~ /^[0-9.]+$/ { v = $1 } END { print v + 0 }'
}

results=()
for spec in "${ENGINES[@]}"; do
    IFS='|' read -r id name sock disk_pat helpers <<<"$spec"
    if [[ -z $sock || ! -S $sock ]] || ! docker -H "unix://$sock" version >/dev/null 2>&1; then
        log "skip $name (no socket: ${sock:-none})"
        continue
    fi
    D=(docker -H "unix://$sock")
    log "== $name ($sock)"

    "${D[@]}" pull -q "$IMAGE" >/dev/null
    running=$("${D[@]}" ps -q | wc -l | tr -d ' ')
    info=$("${D[@]}" info --format '{"server":"{{.ServerVersion}}","os":"{{.OperatingSystem}}","kernel":"{{.KernelVersion}}","cpus":{{.NCPU}},"mem_mib":{{.MemTotal}}}' |
        jq '.mem_mib = (.mem_mib / 1048576 | round)')
    api=$("${D[@]}" version --format '{{.Server.APIVersion}}')

    # 리소스는 벤치 부하(페이지 캐시 등)가 섞이지 않도록 측정 전에 먼저 찍는다
    # 컨테이너 안에서 본 VM 메모리 (Linux 네이티브면 호스트 메모리)
    guest=$("${D[@]}" run --rm "$IMAGE" awk '/MemTotal/ { t = $2 } /MemAvailable/ { a = $2 } END { printf "{\"total_mib\":%d,\"used_mib\":%d}", t / 1024, (t - a) / 1024 }' /proc/meminfo)

    log "  host processes"
    hp="[]"
    seen=" "
    IFS=',' read -ra pats <<<"$helpers"
    for pat in "${pats[@]}"; do
        # gvproxy 인자에 vfkit 소켓 경로가 들어 있듯 패턴이 여러 프로세스에 걸릴 수 있어 pid 로 중복을 없앤다
        for p in $(pgrep -f "$pat" || true); do
            [[ $seen == *" $p "* ]] && continue
            seen+="$p "
            cmd=$(ps -o comm= -p "$p" | xargs basename)
            hp=$(jq --arg c "$cmd" --argjson mb "$(footprint_mb "$p")" --argjson cpu "$(cpu_pct "$p")" \
                '. + [{cmd: $c, mb: $mb, cpu: $cpu}]' <<<"$hp")
        done
    done
    vm="null"
    vp=$(vm_pid_by_disk "$disk_pat")
    if [[ -n $vp ]]; then
        vm=$(jq -n --argjson mb "$(footprint_mb "$vp")" --argjson cpu "$(cpu_pct "$vp")" '{mb: $mb, cpu: $cpu}')
    fi

    log "  api _ping x$PINGS"
    ping=$(for _ in $(seq "$PINGS"); do
        curl -s -o /dev/null -w '%{time_total}\n' --unix-socket "$sock" http://d/_ping
    done | awk '{ print $1 * 1000 }' | stats)

    log "  run --rm x$RUNS"
    run=$(hf "$RUNS" 3 "${D[*]} run --rm $IMAGE true")

    log "  exec x$RUNS"
    "${D[@]}" rm -f crt-bench-exec >/dev/null 2>&1 || true
    "${D[@]}" run -d --name crt-bench-exec "$IMAGE" sleep 600 >/dev/null
    exec_=$(hf "$RUNS" 3 "${D[*]} exec crt-bench-exec true")
    "${D[@]}" rm -f crt-bench-exec >/dev/null

    log "  build (3 layers, --no-cache)"
    mkdir -p "$WORK/build"
    printf 'FROM %s\nRUN echo a > /a\nRUN echo b > /b\nRUN echo c > /c\n' "$IMAGE" >"$WORK/build/Dockerfile"
    builder=buildkit
    if ! "${D[@]}" build -q --no-cache -t crt-bench-build "$WORK/build" >/dev/null 2>&1; then
        builder=legacy
    fi
    if [[ $builder == legacy ]]; then
        build=$(DOCKER_BUILDKIT=0 hf 5 1 "${D[*]} build -q --no-cache -t crt-bench-build $WORK/build")
    else
        build=$(hf 5 1 "${D[*]} build -q --no-cache -t crt-bench-build $WORK/build")
    fi
    "${D[@]}" rmi -f crt-bench-build >/dev/null 2>&1 || true

    # busybox date 는 %N 을 지원하지 않으므로 시간은 dd 자체 출력(µs)과 busybox time(10ms)으로 잰다
    M=(-v "$WORK:/m")
    DD_SEC='sed -n "s/.*copied, \([0-9.]*\) seconds.*/\1/p"'
    log "  bind mount write ${FILE_MB}MiB x$REPS"
    wr=$(for _ in $(seq "$REPS"); do
        "${D[@]}" run --rm "${M[@]}" "$IMAGE" sh -c \
            "dd if=/dev/zero of=/m/w.bin bs=1M count=$FILE_MB conv=fsync 2>&1 | $DD_SEC; rm -f /m/w.bin"
    done | awk -v mb="$FILE_MB" '{ print mb / $1 }' | median)

    log "  bind mount read ${FILE_MB}MiB x$REPS (새 파일)"
    rd=$(for i in $(seq "$REPS"); do
        dd if=/dev/urandom of="$WORK/r$i.bin" bs=1m count="$FILE_MB" 2>/dev/null
        "${D[@]}" run --rm "${M[@]}" "$IMAGE" sh -c \
            "dd if=/m/r$i.bin of=/dev/null bs=1M 2>&1 | $DD_SEC"
        rm -f "$WORK/r$i.bin"
    done | awk -v mb="$FILE_MB" '{ print mb / $1 }' | median)

    log "  small files x$SMALL_FILES x$REPS"
    sf=$(for _ in $(seq "$REPS"); do
        "${D[@]}" run --rm "${M[@]}" "$IMAGE" sh -c \
            "mkdir -p /m/sf; time sh -c 'i=0; while [ \$i -lt $SMALL_FILES ]; do echo \$i > /m/sf/\$i; i=\$((i + 1)); done' 2>&1; rm -rf /m/sf" |
            awk '/^real/ { print ($2 * 60 + $3) * 1000 }'
    done | median)

    results+=("$(jq -n \
        --arg id "$id" --arg name "$name" --arg api "$api" --arg builder "$builder" \
        --argjson info "$info" --argjson running "$running" \
        --argjson ping "$ping" --argjson run "$run" --argjson exec "$exec_" --argjson build "$build" \
        --argjson wr "$wr" --argjson rd "$rd" --argjson sf "$sf" \
        --argjson guest "$guest" --argjson hp "$hp" --argjson vm "$vm" \
        '{id: $id, name: $name, server: $info.server, api: $api, os: $info.os, kernel: $info.kernel,
		  cpus: $info.cpus, mem_mib: $info.mem_mib, containers_running: $running,
		  ping_ms: $ping, run_ms: $run, exec_ms: $exec, build_ms: $build, builder: $builder,
		  bind_write_mbps: ($wr | round), bind_read_mbps: ($rd | round), small_files_ms: ($sf | round),
		  guest_mem: $guest, host_procs: $hp, vm_proc: $vm}')")
done

host=$(jq -n \
    --arg model "$(sysctl -n machdep.cpu.brand_string)" \
    --argjson mem "$(($(sysctl -n hw.memsize) / 1073741824))" \
    --arg os "macOS $(sw_vers -productVersion)" \
    --arg cli "$(docker version --format '{{.Client.Version}}' 2>/dev/null)" \
    '{cpu: $model, mem_gib: $mem, os: $os, docker_cli: $cli}')

printf '%s\n' "${results[@]}" | jq -s \
    --arg at "$(date '+%Y-%m-%d %H:%M')" --argjson host "$host" \
    --argjson cfg "{\"runs\":$RUNS,\"pings\":$PINGS,\"reps\":$REPS,\"file_mib\":$FILE_MB,\"small_files\":$SMALL_FILES}" \
    '{measured_at: $at, host: $host, config: $cfg, engines: .}' >"$OUT"
log "wrote $OUT"
