#!/bin/bash
set -euo pipefail

cdx_state=/tmp/cdx-rpe-b-worker.state
[[ -f "$cdx_state" && ! -L "$cdx_state" && "$(stat -f '%Lp' "$cdx_state")" == 600 ]]
cdx_root="$(awk -F= '$1=="root"{print substr($0,index($0,"=")+1)}' "$cdx_state")"
cdx_pid="$(awk -F= '$1=="pid"{print $2}' "$cdx_state")"
cdx_port="$(awk -F= '$1=="port"{print $2}' "$cdx_state")"
cdx_redis_pid="$(awk -F= '$1=="redis_pid"{print $2}' "$cdx_state")"
[[ "$cdx_root" =~ ^/tmp/cdx-rpe-b-runtime\.[A-Za-z0-9]+$ && -d "$cdx_root" && ! -L "$cdx_root" ]]
[[ "$cdx_pid" =~ ^[0-9]+$ && "$cdx_redis_pid" =~ ^[0-9]+$ && "$cdx_port" == 18082 ]]
if kill -0 "$cdx_pid" 2>/dev/null; then
    kill "$cdx_pid"
    wait "$cdx_pid" 2>/dev/null || true
fi
if kill -0 "$cdx_redis_pid" 2>/dev/null; then
    kill "$cdx_redis_pid"
fi
for _ in {1..100}; do
    if ! kill -0 "$cdx_pid" 2>/dev/null && ! kill -0 "$cdx_redis_pid" 2>/dev/null; then break; fi
    sleep 0.05
done
[[ -z "$(lsof -nP -t -iTCP:18082 -sTCP:LISTEN 2>/dev/null)" ]]
[[ -z "$(lsof -nP -t -iTCP:16379 -sTCP:LISTEN 2>/dev/null)" ]]
rm -f "$cdx_state"
rm -rf "$cdx_root"
printf '{"status":"stopped","worker_removed":true,"redis_removed":true}\n'
