#!/bin/sh

. /lib/functions.sh
. /lib/functions/network.sh

config_load ffwizard
config_get sharenet settings sharenet

[ "$sharenet" = 1 ] || exit

[ "$INTERFACE" = ffuplink ] && [ "$ACTION" = ifup ] && logger -t ff-userlog "OpenVPN connection has been established"
[ "$INTERFACE" = ffuplink ] && [ "$ACTION" = ifdown ] && logger -t ff-userlog "OpenVPN connection went down"

[ "$INTERFACE" = wan ] || exit

config_load openvpn
config_get uci_vpn_enabled ffuplink enabled

if [ "$ACTION" = ifup ]; then
  logger -t ff-userlog "WAN interface is up"
  if [ "$uci_vpn_enabled" = 1 ]; then
    logger -t ff-vpn-hotplug "Starting OpenVPN on WAN interface"
    # Make sure OpenVPN connects only through WAN: set "local" option with WAN IP
    network_get_ipaddr wanip "wan"
    uci set openvpn.ffuplink.local=$wanip
    uci commit openvpn
    /etc/init.d/openvpn start
    exit
  fi
fi

if [ "$ACTION" = ifdown ]; then
  logger -t ff-userlog "WAN interface went down"
    if [ "$uci_vpn_enabled" = 1 ]; then
      logger -t ff-vpn-hotplug "Stopping OpenVPN"
      /etc/init.d/openvpn stop
    exit
  fi
fi

