#!/bin/env bash

if [ "$1" == "help" ]
then
  echo "Usage:"
  echo "./wgconfig.sh [a.b.c.d/sn] [a.b.c.d:port] [server public key] [client private key]"
  echo " - Configures WireGuard on the given ip to connect to the servers ip and port with the given public and private key"
  echo "./wgconfig.sh add-sn [a.b.c.d/sn]"
  echo " - Adds a route to a local subnet"
  exit 0
fi

if [ "$1" == "add-sn" ]
then
  ip route add $2 dev wg0
  exit 0
fi

if [[ -z $1 ]]
then
  echo "Missing arguments. Usage: ./wgconfig.sh [a.b.c.d/sn] [a.b.c.d:port] [server public key] [client private key]"
  exit 0
fi

if [[ -z $2 ]]
then
  echo "Missing arguments. Usage: ./wgconfig.sh [a.b.c.d/sn] [a.b.c.d:port] [server public key] [client private key]"
  exit 0
fi

if [[ -z $3 ]]
then
  echo "Missing arguments. Usage: ./wgconfig.sh [a.b.c.d/sn] [a.b.c.d:port] [server public key] [client private key]"
  exit 0
fi

if [[ -z $4 ]]
then
  echo "Missing arguments. Usage: ./wgconfig.sh [a.b.c.d/sn] [a.b.c.d:port] [server public key] [client private key]"
  exit 0
fi

if [ $(dpkg-query -W -f='${Status}' nano 2>/dev/null | grep -c "ok installed") -eq 0 ]
then
  echo "Wireguard not found, installing it now..."
  apt-get install wireguard
fi

echo $4 > /etc/wireguard/privateKey
ip link add wg0 type wireguard
ip address add $1 dev wg0
wg set wg0 private-key /etc/wireguard/privateKey peer $3 endpoint $2 allowed-ips 172.16.0.0/24,10.0.0.0/8
ip link set dev wg0 up
