#!/bin/sh /etc/rc.common

USE_PROCD=1
START=95
STOP=01

apply_glinet_kmwan() {
  uci commit kmwan
  /etc/init.d/kmwan restart
}

disable_glinet_kmwan() {
  local need_apply=0
  # Do nothing if we aren't on a glinetos device with kmwan
  if ! uci -q get kmwan.global.enable; then
    return 0
  fi
  # If kmwan has "priority" over speedify/escape hatch, enable it globally (but leave individual network checks disabled)
  if test "$(uci -q get kmwan.global.speedify_has_priority || echo 1)" != 1; then
    logger -t speedify "kmwan has priority over speedify, enabling kmwan globally"
    uci set kmwan.global.enable='1'
    apply_glinet_kmwan
    return 0
  fi
  if test "$(uci -q get kmwan.global.enable)" != 0; then
    logger -t speedify "Disabling kmwan globally"
    uci set kmwan.global.enable='0'
    need_apply=1
  fi
  for nw in $(uci show kmwan | grep -E 'kmwan\..+=member' | cut -d= -f1 | cut -d. -f2 | tr "\n" ' '); do
    if test "$(uci -q get kmwan."$nw".check || echo 1)" != 0 || test "$(uci -q get kmwan."$nw".disabled || echo 0)" != 1; then
      logger -t speedify "Disabling kmwan connectivity check on network $nw"
      uci set kmwan.$nw.check='0'
      uci set kmwan.$nw.disabled='1'
      need_apply=1
    else
      logger -t speedify "Network $nw kmwan already disabled"
    fi
  done
  if test "$need_apply" -eq 1; then
    apply_glinet_kmwan
  fi
}

start_service() {
  disable_glinet_kmwan
  ifup speedify
  procd_open_instance speedify
  if [ -d /usr/share/speedify/logs ]; then
    mkdir -p /etc/speedify
    mv /usr/share/speedify/logs/* /etc/speedify/
    rm -rf /usr/share/speedify/logs
  fi
  if [ -d /etc/config/speedify_native ]; then
    mkdir -p /etc/speedify
    mv /etc/config/speedify_native/* /etc/speedify/
    rm -rf /etc/config/speedify_native
  fi
  procd_set_param command /usr/share/speedify/speedify -d /etc/speedify/ -r /usr/share/speedify -g /tmp/speedify-logs -k /etc/.speedify/
  procd_set_param user root
  # Respawn automatically if it died.
  # - If the process exits sooner than respawn_threshold, it is considered crashed.
  #   It will retry respawn_retry times to get past the threshold. Else the service is stopped.
  # - If the process finishes later than respawn_threshold, it is restarted unconditionally,
  #   regardless of error code. Notice that this is literal respawning of the process, not in a
  #   respawn-on-failure sense. Like a task that needs to be run periodically.
  procd_set_param respawn ${respawn_threshold:-60} ${respawn_timeout:-5} ${respawn_retry:-5}
  procd_close_instance
}

stop_service() {
  ifdown speedify
}
