#!/bin/sh
[ -n "${IPKG_INSTROOT}" ] || {
  detect_mips_endian() {
    local byte
    byte=$(hexdump -s 5 -n 1 -e '"%d"' /bin/busybox 2>/dev/null)
    if [ "$byte" = "1" ]; then
      echo "mipsel"
    else
      echo "mips"
    fi
  }

  ARCH=$(uname -m)
  case "$ARCH" in
    x86_64)  BIN="netflow_x86_64" ;;
    aarch64) BIN="netflow_aarch64" ;;
    armv7*)  BIN="netflow_arm" ;;
    arm*)    BIN="netflow_arm" ;;
    mips|mipsel)
      REAL_MIPS=$(detect_mips_endian)
      BIN="netflow_${REAL_MIPS}"
      ;;
    *)
      REAL_MIPS=$(detect_mips_endian)
      if [ "$REAL_MIPS" = "mipsel" ] || [ "$REAL_MIPS" = "mips" ]; then
        BIN="netflow_${REAL_MIPS}"
      else
        BIN="netflow_x86_64"
      fi
      ;;
  esac

  rm -f /usr/bin/netflow
  if [ -x "/usr/bin/${BIN}" ]; then
    ln -sf "/usr/bin/${BIN}" /usr/bin/netflow
    echo "NetFlow: linked ${BIN} -> /usr/bin/netflow (arch: ${ARCH})"
  else
    echo "WARNING: binary /usr/bin/${BIN} not found for arch ${ARCH}"
  fi

  mkdir -p /etc/netflow/mihomo
  mkdir -p /etc/netflow/v2board

  if [ ! -f /etc/netflow/.dev_salt ] || [ ! -s /etc/netflow/.dev_salt ]; then
    head -c 32 /dev/urandom | hexdump -e '32/1 "%02x"' > /etc/netflow/.dev_salt
    chmod 600 /etc/netflow/.dev_salt
  fi

  rm -rf /tmp/luci-indexcache /tmp/luci-modulecache

  # Stop old service before starting new one (upgrade scenario)
  /etc/init.d/netflow stop 2>/dev/null
  killall netflow 2>/dev/null
  sleep 1

  if [ -x /etc/uci-defaults/luci-app-netflow ]; then
    /etc/uci-defaults/luci-app-netflow
  else
    /etc/init.d/netflow enable
    /etc/init.d/netflow start
  fi
}
exit 0
