#!/usr/bin/env bash
# lp-resolve start | render <in_dir> <out_dir> | shot <png> | stop | desktop
# Resolve runs as user editor on display :99 (Xvfb) with OpenGL redirected to the NVIDIA GPU through VirtualGL (EGL).
export DISPLAY=:99
U="sudo -u editor -H env DISPLAY=:99"
win() { xdotool search --name "DaVinci Resolve" 2>/dev/null | head -1; }
start() {
  pgrep -x Xvfb >/dev/null || (Xvfb :99 -screen 0 1920x1080x24 +extension GLX >/tmp/xvfb.log 2>&1 &) ; sleep 2
  if ! pgrep -f /opt/resolve/bin/resolve >/dev/null; then
    $U bash -c 'nohup vglrun -d egl /opt/resolve/bin/resolve >/tmp/resolve.log 2>&1 &'
  fi
  for i in $(seq 1 180); do
    touch /run/lp/heartbeat 2>/dev/null
    w=$(win); if [ -n "$w" ]; then
      # dismiss first-run dialogs (welcome / quick setup / project manager): Enter/Escape on whatever has focus
      sleep 5; return 0; fi
    pgrep -f /opt/resolve/bin/resolve >/dev/null || { echo "LP_FAIL: resolve exited"; tail -30 /tmp/resolve.log; return 1; }
    sleep 2
  done
  echo "LP_FAIL: no Resolve window after 360 s"; return 1
}
api_python() {  # external scripting (Studio feature on most versions); returns 0 if it rendered
  PYTHONPATH=/opt/resolve/Developer/Scripting/Modules RESOLVE_SCRIPT_API=/opt/resolve/Developer/Scripting \
  RESOLVE_SCRIPT_LIB=/opt/resolve/libs/Fusion/fusionscript.so timeout 30 python3 -c 'import DaVinciResolveScript as d,sys; r=d.scriptapp("Resolve"); sys.exit(0 if r else 3)' 2>/dev/null
}
run_menu_script() {  # in-app: Workspace > Scripts > lp_render (free version path)
  w=$(win); [ -n "$w" ] || return 1
  xdotool windowactivate --sync $w 2>/dev/null; xdotool windowfocus $w
  # open the Workspace menu by clicking its title in the menu bar, then Scripts, then lp_render
  eval $(xdotool getwindowgeometry --shell $w)
  python3 /opt/lp/image/menu_click.py "Workspace" "Scripts" "lp_render"
}
case "${1:-}" in
  start) start ;;
  stop) pkill -f /opt/resolve/bin/resolve; pkill Xvfb; echo stopped ;;
  shot) import -display :99 -window root "${2:-/work/resolve/screen.png}" && echo "${2:-/work/resolve/screen.png}" ;;
  render)
    in=${2:?in dir}; out=${3:?out dir}; mkdir -p "$out"; chown -R editor:editor /work
    printf '%s\n%s\n' "$in" "$out" > /work/resolve/job.txt; rm -f /work/resolve/result.txt
    start || exit 1
    if api_python; then
      echo "external scripting available"; sudo -u editor -H env PYTHONPATH=/opt/resolve/Developer/Scripting/Modules RESOLVE_SCRIPT_LIB=/opt/resolve/libs/Fusion/fusionscript.so \
        /opt/resolve/libs/Fusion/fuscript -l lua /home/editor/.local/share/DaVinciResolve/Fusion/Scripts/Utility/lp_render.lua
    else
      run_menu_script || { echo "LP_FAIL: could not trigger the in-app script"; exit 1; }
    fi
    for i in $(seq 1 600); do [ -s /work/resolve/result.txt ] && break; touch /run/lp/heartbeat; sleep 2; done
    cat /work/resolve/result.txt 2>/dev/null || { echo "LP_FAIL: no result"; exit 1; }
    ls -la "$out" ;;
  desktop)
    pgrep -x x11vnc >/dev/null || x11vnc -display :99 -localhost -forever -shared -nopw -bg -o /tmp/x11vnc.log >/dev/null 2>&1
    ss -ltn | grep -q '127.0.0.1:6080 ' || setsid -f websockify --web /usr/share/novnc 127.0.0.1:6080 127.0.0.1:5900 >/tmp/novnc.log 2>&1 </dev/null
    echo "noVNC on 127.0.0.1:6080/vnc.html" ;;
  *) echo "usage: lp-resolve start|render IN OUT|shot PNG|stop|desktop"; exit 2 ;;
esac
