#!/bin/sh

# Sets up the wireguard interface and begins logging

error_exit()
{
  echo "${1:-"Unknown Error"}" 1>&2
  exit 1
}

setup_interface()
{
  ip link show dev ${WIREGUARD_INTERFACE_NAME}
  if [ $? -ne 0 ]; then
    ip link add ${WIREGUARD_INTERFACE_NAME} type wireguard
  fi

  if [ $WIREGUARD_IPV4_ENABLED = "true" ]; then
    ip address replace ${WIREGUARD_IPV4_ADDRESS} dev ${WIREGUARD_INTERFACE_NAME}
  fi
  if [ $WIREGUARD_IPV6_ENABLED = "true" ]; then
    ip -6 address replace ${WIREGUARD_IPV6_ADDRESS} dev ${WIREGUARD_INTERFACE_NAME}
  fi
  ip link set mtu ${WIREGUARD_INTERFACE_MTU} up dev ${WIREGUARD_INTERFACE_NAME}
}

add_routes()
{
  if [ $WIREGUARD_IPV4_ENABLED = "true" ]; then
    ip route add ${WIREGUARD_IPV4_NETWORK} dev ${WIREGUARD_INTERFACE_NAME}
  fi
  if [ $WIREGUARD_IPV6_ENABLED = "true" ]; then
    ip -6 route add ${WIREGUARD_IPV6_NETWORK} dev ${WIREGUARD_INTERFACE_NAME}
  fi
}

main()
{
  if [ $LOGGING_ENABLED = "true" ]; then
    echo 'Enabling WireGuard debugging support...'
    echo module wireguard +p > /sys/kernel/debug/dynamic_debug/control
    if [ $? -eq 0 ]; then
      echo 'WireGuard debugging enabled. Starting dmesg...'
      dmesg -wT | grep "wireguard: ${WIREGUARD_INTERFACE_NAME}:"
    else
      echo 'There was an issue enabling WireGuard debugging. Twiddling my thumbs...'
      tail -f /dev/null
    fi
  else
    tail -f /dev/null
  fi
}

setup_interface
add_routes
main
