#!/bin/sh
# Starts, stops and reports KumoYami, a Node.js server (target/node/bin/node target/app/kumoyami.js) that runs as the
# package's user in the background, in a session of its own, with its pid in the package's var folder. Its output
# goes to logs/kumoyami.log in the data folder, which the owner can open in File Station (the first-run setup code is
# there); the lines of this script go to the package's log, /var/log/packages/kumoyami.log. DSM runs the actions
# start, stop, status (0 running, 3 stopped), prestart and prestop
# (https://help.synology.com/developer-guide/synology_package/scripts.html).
. "$(dirname "$0")/common"

DEST="${SYNOPKG_PKGDEST:-/var/packages/$PKG/target}"
PIDFILE="$PKGVAR/$PKG.pid"
NODE="$DEST/node/bin/node"
# Seconds a stop waits for the server to end before killing it
STOP_WAIT=20
LOG_MAX_BYTES=5242880

# The pid of the running server, if it is ours: alive, and running the package's node (a pid file left by a crash may
# name another process by now)
server_pid() {
  [ -r "$PIDFILE" ] || return 1
  pid=$(cat "$PIDFILE" 2>/dev/null)
  case "$pid" in '' | *[!0-9]*) return 1 ;; esac
  kill -0 "$pid" 2>/dev/null || return 1
  exe=$(readlink "/proc/$pid/exe" 2>/dev/null)
  if [ -n "$exe" ] && [ "$exe" != "$NODE" ] && [ "$exe" != "$(readlink -f "$NODE")" ]; then
    # Under QEMU's user emulation (the armv8 package tried on an x86-64 machine, smoke-test.sh) exe is the emulator,
    # and the command line still names the package's node
    tr '\0' '\n' < "/proc/$pid/cmdline" 2>/dev/null | grep -qxF -e "$NODE" -e "$(readlink -f "$NODE")" || return 1
  fi
  echo "$pid"
}

# Every process still running a program of the package (ffmpeg started by the server, the server itself), for the end
# of a stop
package_pids() {
  real=$(cd "$DEST" 2>/dev/null && pwd -P)
  for p in /proc/[0-9]*; do
    exe=$(readlink "$p/exe" 2>/dev/null) || continue
    # Under QEMU's user emulation (smoke-test.sh of armv8) the program is the second word of the command line
    case "$exe" in */qemu-*) exe=$(tr '\0' '\n' < "$p/cmdline" 2>/dev/null | sed -n 2p) ;; esac
    case "$exe" in "$DEST"/* | "${real:-$DEST}"/*) echo "${p#/proc/}" ;; esac
  done
}

# The settings and the data folder: DATA_DIR, LOG_FILE
load_settings() {
  settings=$(find_settings) || {
    log "no $SETTINGS_NAME: reinstall the package"
    return 1
  }
  DATA_SHARE=$(setting "$settings" DATA_SHARE)
  DATA_SUBFOLDER=$(setting "$settings" DATA_SUBFOLDER)
  PORT=$(setting "$settings" PORT)
  TIMEZONE=$(setting "$settings" TIMEZONE)
  PORT="${PORT:-4890}"
  TIMEZONE="${TIMEZONE:-Europe/Madrid}"
  # The install wizard's GPU box, as the app's hardware acceleration until the owner picks one in its panel: «auto»
  # (the GPU when it works) or «off» (the processor only). An install from before the box has no GPU line: auto.
  if [ "$(setting "$settings" GPU)" = no ]; then HWACCEL=off; else HWACCEL=auto; fi
  # The data shared folder, created by the data-share worker when the package was enabled
  base=$(share_path "$DATA_SHARE") || {
    log "the data shared folder $DATA_SHARE does not exist"
    return 1
  }
  DATA_DIR="$base${DATA_SUBFOLDER:+/$DATA_SUBFOLDER}"
  mkdir -p "$DATA_DIR" 2>/dev/null
  if [ ! -w "$DATA_DIR" ] || { [ -e "$DATA_DIR/kv.json" ] && [ ! -w "$DATA_DIR/kv.json" ]; }; then
    log "$DATA_DIR is not writable by $(id -un 2>/dev/null || id -u): Control Panel → Shared Folder → $DATA_SHARE → Edit → Permissions → System internal user → $PKG → Read/Write"
    return 1
  fi
  # The server's output, where File Station shows it; the package's var folder when the data folder has no room for it
  if mkdir -p "$DATA_DIR/logs" 2>/dev/null && [ -w "$DATA_DIR/logs" ]; then
    LOG_FILE="$DATA_DIR/logs/kumoyami.log"
  else
    LOG_FILE="$PKGVAR/kumoyami.log"
  fi
}

# The volumes and the shared folders the package's user cannot read now, for the app's folder picker (SYNOLOGY_VOLUMES)
# and the log. The app checks each folder itself when it lists a volume, so a folder the owner allows later shows at
# once; SYNOLOGY_LOCKED (which names folders a container could not see) stays empty: here every folder is visible.
nas_paths() {
  VOLUMES=""
  LOCKED=""
  for v in $(nas_volumes); do VOLUMES="$VOLUMES${VOLUMES:+,}$v"; done
  all_shares=$(nas_shares)
  while IFS= read -r d; do
    [ -n "$d" ] || continue
    if [ ! -r "$d" ] || [ ! -x "$d" ]; then LOCKED="$LOCKED${LOCKED:+,}$d"; fi
  done <<SHARES
$all_shares
SHARES
}

# What the log needs to tell whether the GPU can be used: the groups of this user (videodriver is added by the
# video-driver worker, conf/resource) and the device files
gpu_report() {
  log "user: $(id 2>&1)"
  if [ -d /dev/dri ]; then
    # shellcheck disable=SC2012 # a listing for people to read
    log "/dev/dri: $(ls -ln /dev/dri 2>&1 | awk 'NR > 1 { printf "%s %s:%s %s; ", $1, $3, $4, $NF }')"
    for dev in /dev/dri/renderD*; do
      [ -e "$dev" ] || continue
      if [ -r "$dev" ] && [ -w "$dev" ]; then log "$dev: readable and writable"; else log "$dev: NOT accessible (videos are converted by the processor)"; fi
    done
    vainfo_report
  else
    log "/dev/dri: none (no GPU: videos are converted by the processor)"
  fi
}

# Which driver libva tries and whether it loads, from the package's vainfo on the first render node: the lines that
# tell the driver path and the outcome. It never stops the start. The ARM package (armv8) has no GPU stack nor vainfo.
vainfo_report() {
  [ -x "$DEST/ffmpeg/vainfo" ] || return 0
  for dev in /dev/dri/renderD*; do
    [ -r "$dev" ] && [ -w "$dev" ] || continue
    runner=""
    command -v timeout >/dev/null 2>&1 && runner="timeout 10"
    # shellcheck disable=SC2086 # $runner is a command or nothing
    $runner "$DEST/bin/vainfo" --display drm --device "$dev" 2>&1 |
      grep -E 'VA-API version|Trying to open|Found init function|va_openDriver|Driver version|vaInitialize|error' |
      head -n 8 | while IFS= read -r line; do log "vainfo: $line"; done
    return 0
  done
}

start_server() {
  if pid=$(server_pid); then
    log "already running (pid $pid)"
    return 0
  fi
  rm -f "$PIDFILE"
  load_settings || return 1
  nas_paths
  mkdir -p "$PKGVAR/cache" "$PKGVAR/tmp"

  # Node.js needs the C++ runtime (libstdc++ with GLIBCXX_3.4.25 or later); DSM 7.2 has one. If this DSM's does not do,
  # the copy from the package (target/ffmpeg/lib, Debian bookworm's) is used for node too.
  lib_path=""
  if ! "$NODE" -e 0 2>/dev/null; then
    if LD_LIBRARY_PATH="$DEST/ffmpeg/lib" "$NODE" -e 0 2>/dev/null; then
      lib_path="$DEST/ffmpeg/lib"
      log "node: DSM's C++ runtime does not do, the package's is used"
    else
      log "node cannot run: $("$NODE" -e 0 2>&1 | head -n 3)"
      return 1
    fi
  fi

  # A log that has grown too much starts again; the previous one is kept as kumoyami.log.1
  if [ -f "$LOG_FILE" ] && [ "$(wc -c < "$LOG_FILE")" -gt "$LOG_MAX_BYTES" ]; then
    mv -f "$LOG_FILE" "$LOG_FILE.1"
  fi
  log "start: port $PORT, data $DATA_DIR, log $LOG_FILE, volumes ${VOLUMES:-none}; shared folders $PKG cannot read: ${LOCKED:-none}"
  # (the device report is logged either way: the panel can still turn the GPU on)
  [ "$HWACCEL" = off ] && log "GPU box unticked in the install wizard: KUMOYAMI_HWACCEL=off (the processor converts unless the panel says otherwise)"
  gpu_report
  printf '\n%s KumoYami Server %s starting (port %s, data %s)\n' "$(date '+%Y-%m-%d %H:%M:%S')" \
    "${SYNOPKG_PKGVER:-}" "$PORT" "$DATA_DIR" >> "$LOG_FILE"

  # A clean environment: only what the server needs. setsid gives it a session (and process group) of its own, so that
  # a stop reaches the programs it started too.
  session=""
  command -v setsid >/dev/null 2>&1 && session=setsid
  cd "$DEST/app" || return 1
  # shellcheck disable=SC2086 # $session is a command or nothing
  env -i \
    PATH="$DEST/bin:/usr/bin:/bin:/usr/sbin:/sbin" \
    HOME="$PKGVAR" \
    LANG=C.UTF-8 \
    TZ="$TIMEZONE" \
    TMPDIR="$PKGVAR/tmp" \
    XDG_CACHE_HOME="$PKGVAR/cache" \
    ${lib_path:+LD_LIBRARY_PATH="$lib_path"} \
    NODE_ENV=production \
    NEXT_TELEMETRY_DISABLED=1 \
    HOSTNAME=0.0.0.0 \
    PORT="$PORT" \
    DATA_DIR="$DATA_DIR" \
    FFMPEG_PATH="$DEST/bin/ffmpeg" \
    FFPROBE_PATH="$DEST/bin/ffprobe" \
    FONTCONFIG_FILE="$DEST/fonts/fonts.conf" \
    SYNOLOGY_VOLUMES="$VOLUMES" \
    SYNOLOGY_LOCKED="" \
    SYNOLOGY_NATIVE=1 \
    KUMOYAMI_HWACCEL="$HWACCEL" \
    KUMOYAMI_LOG_FILE="$LOG_FILE" \
    $session "$NODE" kumoyami.js >> "$LOG_FILE" 2>&1 < /dev/null &
  echo $! > "$PIDFILE"

  # A server that cannot start (port taken, a broken data folder) ends within a few seconds: Package Center then shows
  # it as stopped, and the reason is in both logs
  i=0
  while [ "$i" -lt 5 ]; do
    sleep 1
    if ! server_pid > /dev/null; then
      log "the server stopped right after starting; the end of $LOG_FILE:"
      tail -n 20 "$LOG_FILE" | sed 's/^/    | /' >&2
      rm -f "$PIDFILE"
      return 1
    fi
    i=$((i + 1))
  done
  touch "$PKGVAR/$RAN_NAME" 2>/dev/null
  log "started (pid $(cat "$PIDFILE"))"
}

stop_server() {
  if pid=$(server_pid); then
    log "stop (pid $pid)"
    # The whole process group when it has its own (setsid), else the server alone; `kill -TERM -<pgid>` is the form
    # dash, bash and BusyBox all take (dash refuses `--`). The group is the fifth field of
    # /proc/<pid>/stat, the third after the program's name in parentheses (proc(5)).
    group=$(sed 's/.*) //' "/proc/$pid/stat" 2>/dev/null | cut -d ' ' -f 3)
    if [ "$group" = "$pid" ]; then target="-$pid"; else target="$pid"; fi
    kill -TERM "$target" 2>/dev/null
    i=0
    while [ "$i" -lt "$STOP_WAIT" ] && kill -0 "$pid" 2>/dev/null; do
      sleep 1
      i=$((i + 1))
    done
    if kill -0 "$pid" 2>/dev/null; then
      log "still running after ${STOP_WAIT}s: killed"
      kill -KILL "$target" 2>/dev/null
    fi
  fi
  rm -f "$PIDFILE"
  # Whatever the server started that is still there (an ffmpeg conversion outside its group)
  left=$(package_pids)
  if [ -n "$left" ]; then
    log "stopping what is left: $(echo "$left" | tr '\n' ' ')"
    # shellcheck disable=SC2086 # one pid per word
    kill -TERM $left 2>/dev/null
    sleep 2
    # shellcheck disable=SC2086
    kill -KILL $left 2>/dev/null
  fi
  return 0
}

case "$1" in
  start)
    start_server || exit 1
    ;;
  stop)
    stop_server
    ;;
  status)
    server_pid > /dev/null || exit 3
    ;;
  prestart | prestop) ;;
  *)
    echo "Usage: $0 {start|stop|status}" >&2
    exit 1
    ;;
esac
exit 0
