#!/usr/bin/env bash
# ═══════════════════════════════════════════════════════════════════════════
#  uopi test SoftIOC startup script
#
#  Prerequisites:
#    • EPICS Base 3.15+ (for RNDM calc function)
#    • 'softIoc' binary in PATH  (usually $EPICS_BASE/bin/$EPICS_HOST_ARCH/)
#    • Optional: caput (from EPICS tools) to pre-fill UOPI:WAVEFORM
#
#  Usage:
#    cd workspace/softioc
#    ./st.cmd
#
#  Or directly (no waveform pre-fill):
#    softIoc -s -d workspace/softioc/uopi_test.db
# ═══════════════════════════════════════════════════════════════════════════

set -euo pipefail
cd "$(dirname "$0")"

# ── Locate softIoc ────────────────────────────────────────────────────────────
if ! command -v softIoc &>/dev/null; then
    # Try common EPICS install paths
    for candidate in \
        "$EPICS_BASE/bin/$EPICS_HOST_ARCH/softIoc" \
        /usr/local/epics/base/bin/linux-x86_64/softIoc \
        /opt/epics/bin/linux-x86_64/softIoc; do
        if [ -x "$candidate" ]; then
            export PATH="$(dirname "$candidate"):$PATH"
            break
        fi
    done
fi

if ! command -v softIoc &>/dev/null; then
    echo "ERROR: softIoc not found. Set EPICS_BASE or add softIoc to PATH."
    exit 1
fi

echo "Starting uopi test IOC…"
echo "  PV prefix : UOPI:"
echo "  Database  : uopi_test.db"
echo "  softIoc   : $(command -v softIoc)"
echo ""

# ── Start IOC in background so we can run caput for waveform ─────────────────
softIoc -s -d uopi_test.db &
IOC_PID=$!

# ── Pre-fill UOPI:WAVEFORM with a sine+DC pattern (requires caput) ───────────
if command -v caput &>/dev/null; then
    sleep 2   # wait for IOC to initialise Channel Access

    python3 - <<'PYEOF'
import subprocess, math

n = 64
# Sine with 3 harmonics: models a realistic ADC capture
vals = [
    0.5 + 0.4 * math.sin(2 * math.pi * i / n)
        + 0.1 * math.sin(6 * math.pi * i / n)
        + 0.05 * math.sin(10 * math.pi * i / n)
    for i in range(n)
]
args = ["caput", "-a", "UOPI:WAVEFORM", str(n)] + [f"{v:.6f}" for v in vals]
result = subprocess.run(args, capture_output=True, text=True)
if result.returncode == 0:
    print(f"  UOPI:WAVEFORM filled with {n}-point multi-harmonic sine.")
else:
    print(f"  caput failed: {result.stderr.strip()}")
PYEOF
else
    echo "  (caput not found — UOPI:WAVEFORM left empty; fill manually via caput)"
fi

echo ""
echo "IOC running (PID $IOC_PID). Connect uopi with:"
echo "  UOPI_EPICS_CA_ADDR_LIST=127.0.0.1 ./dist/uopi -config workspace/uopi.toml"
echo ""
echo "Press Ctrl-C to stop."
wait "$IOC_PID"
