#!/bin/sh

alterator_api_version=1
. alterator-sh-functions
. /usr/lib/alterator-net-iptables/srv.sh

po_domain="alterator-net-iptables"

BASEDIR="/etc/net/ifaces/default/fw/iptables"

INPUT="filter/INPUT"
OUTPUT="filter/OUTPUT"
FORWARD="filter/FORWARD"
NAT_POST="nat/POSTROUTING"
NAT_PRE="nat/PREROUTING"
NAT_OUT="nat/OUTPUT"
MANG_POST="mangle/POSTROUTING"
MANG_PRE="mangle/PREROUTING"
MANG_OUT="mangle/OUTPUT"
MANG_INP="mangle/INPUT"
MANG_FRW="mangle/FORWARD"

ALL_TABLES="$INPUT $OUTPUT $FORWARD
            $NAT_POST $NAT_PRE $NAT_OUT
            $MANG_POST $MANG_PRE $MANG_OUT $MANG_INP $MANG_FRW"

check_name(){
  local name="$1"
  for i in $ALL_TABLES; do
    [ "$name" != "$i" ] || return 0
  done
  return 1
}

run_efw(){
  local table="$1"
  local chain="$2"
  /etc/net/scripts/contrib/efw --iptables default restart | grep '^ERROR'
}

on_message(){
  set_locale
  case "$in_action" in
    list) # list all config files
      for i in $ALL_TABLES; do
        write_enum_item "$i"
      done
    ;;
    read) # read data for selected ip=mac
      [ "$(iptables_helper show -c)" = "on" ] &&
        write_bool_param "status" "off" ||
        write_bool_param "status" "on"
      check_name "$in_name" || write_error "`_ "bad table"`"
      write_string_param "text" "$(cat "$BASEDIR/$in_name")"
    ;;
    write)
      check_name "$in_name" || write_error "`_ "bad table"`"
      printf "%s\n" "$in_text" > "$BASEDIR/$in_name"
      local table="${in_name%/*}"
      local chain="${in_name#*/}"
      local ans="$(run_efw 2>&1)"
      [ -z "$ans" ] || write_error "$ans"
    ;;
    switch)
      if [ "$in_status" = "#t" ]; then
        local ans="$(iptables_helper write -c off 2>&1)"
        [ -z "$ans" ] || write_error "${ans#iptables_helper*:}"
      else
        local ans="$(iptables_helper write -c on 2>&1)"
        [ -z "$ans" ] || write_error "${ans#iptables_helper*:}"
      fi
    ;;
  esac
}

message_loop
