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

#
# Startup/shutdown script for opennds captive portal
#

START=15
STOP=99

USE_PROCD=1

# Run in PROCD (-f) and log to SYSLOG (-s)
OPTIONS="-f -s"
#

CONFIG=""


addline() {
  append CONFIG "$1" "$N"
}

setup_mac_lists() {
  local cfg="$1"
  local macs=""
  local val

  append_mac() {
    append macs "$1" ","
  }

  macs=""
  config_list_foreach "$cfg" trustedmac append_mac
  if [ -n "$macs" ]; then
    addline "TrustedMACList $macs"
  fi

  return 0
}

setup_firewall() {
  local cfg="$1"
  local uci_name
  local val

  append_firewall() {
    addline "  FirewallRule $1"
  }

  for rule in authenticated-users preauthenticated-users users-to-router trusted-users trusted-users-to-router; do
    # uci does not allow dashes
    uci_name=${rule//-/_}
    addline "FirewallRuleSet $rule {"
    config_list_foreach "$cfg" "$uci_name" append_firewall
    addline "}"
    config_get val "$cfg" "policy_${uci_name}"
    if [ -n "$val" ]; then
      addline "EmptyRuleSetPolicy $rule $val"
    fi
  done
}

generate_uci_config() {
  local cfg="$1"
  local val
  local ifname
  local download
  local upload

  # Init config file content
  CONFIG="# auto-generated config file from /etc/config/opennds"

  config_get val "$cfg" config
  if [ -n "$val" ]; then
    if [ ! -f "$val" ]; then
      echo "Configuration file '$file' doesn't exist." >&2
      return 1
    fi
    addline "$(cat $val)"
  fi

  config_get ifname "$cfg" gatewayinterface

  if [ ! -z "$ifname" ]; then
     addline "GatewayInterface $ifname"
  fi

  for option in \
	gatewayname gatewayinterface gatewayaddress gatewayport gatewayfqdn \
	use_outdated_mhd allow_preemptive_authentication unescape_callback_enabled \
	log_mountpoint max_log_entries debuglevel maxclients max_page_size webroot statuspath \
	login_option_enabled preauth binauth themespec_path remotes_refresh_interval \
	fasport faskey fasremotefqdn fasremoteip faspath fas_secure_enabled \
	fas_custom_parameters_list fas_custom_variables_list \
	fas_custom_images_list fas_custom_files_list \
	walledgarden_fqdn_list walledgarden_port_list \
	sessiontimeout preauthidletimeout authidletimeout checkinterval \
	ratecheckwindow downloadrate uploadrate download_bucket_ratio upload_bucket_ratio downloadquota uploadquota \
	max_download_bucket_size max_upload_bucket_size upload_unrestricted_bursting download_unrestricted_bursting \
	syslogfacility ndsctlsocket \
	dhcp_default_url_enable enable_serial_number_suffix \
	fw_mark_authenticated fw_mark_blocked fw_mark_trusted
  do

    config_get val "$cfg" "$option"

    if [ -n "$val" ]; then
      addline "$option $val"
    fi
  done

  setup_mac_lists "$cfg" || return 1
  setup_firewall "$cfg"

  echo "$CONFIG" > "/tmp/etc/opennds_$cfg.conf"
  return 0
}

# setup configuration and start instance
create_instance() {
  local cfg="$1"
  local val

  config_get_bool val "$cfg" enabled 0
  [ $val -gt 0 ] || return 0

  if ! generate_uci_config "$cfg"; then
    echo "Can not generate uci config. Will not start instance $cfg." >&2
    return 1
  fi

  procd_open_instance $cfg
  procd_set_param command /usr/bin/opennds -c "/tmp/etc/opennds_$cfg.conf" $OPTIONS
  procd_set_param respawn
  procd_set_param file "/tmp/etc/opennds_$cfg.conf"
  procd_close_instance
}

start_service() {
  # For network_get_device()
  include /lib/functions

  # For opennds.conf file
  mkdir -p /tmp/etc/

  config_load opennds
  config_foreach create_instance opennds

  /usr/lib/opennds/libopennds.sh users_to_router allow
}

stop_service() {
  # When procd terminates opennds, it does not exit fast enough.
  # Otherwise procd will restart opennds twice. First time starting
  # opennds fails, second time it succeeds.
  sleep 1
  /usr/lib/opennds/libopennds.sh users_to_router cleanup
}
