#!/bin/sh

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

po_domain="alterator-net-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"

setup_vars()
{
  local iptables=

  if [ "$1" = 6 ]; then
      IPTABLES=ip6tables
      ALL_TABLES="$INPUT $OUTPUT $FORWARD
                  $MANG_POST $MANG_PRE $MANG_OUT $MANG_INP $MANG_FRW"
  else
      IPTABLES=iptables
      ALL_TABLES="$INPUT $OUTPUT $FORWARD
                  $NAT_POST $NAT_PRE $NAT_OUT
                  $MANG_POST $MANG_PRE $MANG_OUT $MANG_INP $MANG_FRW"
  fi

  BASEDIR="/etc/net/ifaces/default/fw/$IPTABLES"
  IPTABLES_HELPER_CONF="/etc/alterator/net-$IPTABLES.conf"
}

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"
  local restart_network="$(shell_config_get "$IPTABLES_HELPER_CONF" restart_network)"
  if [ "$restart_network" = "on" ]; then
    service network restart 2>&1 | grep '^ERROR'
  else
    /etc/net/scripts/contrib/efw --$IPTABLES default restart | grep '^ERROR'
  fi
}

on_message(){
  set_locale
  setup_vars "$in_ipv"
  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 -"$in_ipv" 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 -"$in_ipv" write -c off 2>&1)"
        [ -z "$ans" ] || write_error "${ans#iptables_helper*:}"
      else
        local ans="$(iptables_helper -"$in_ipv" write -c on 2>&1)"
        [ -z "$ans" ] || write_error "${ans#iptables_helper*:}"
      fi
    ;;
  esac
}

message_loop
