#!/bin/bash
#
# Wireguard / VPN Service

PATH=$HOME/.docker/cli-plugins:/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

config_wireguard() {
  echo -ne "\n* Configuring /federated/apps/wireguard container.."
  spin &
  SPINPID=$!

  if [ ! -d "/federated/apps/wireguard" ]; then
    mkdir -p /federated/apps/wireguard/data/config/coredns
  fi

cat > /federated/apps/wireguard/docker-compose.yml <<EOF
version: "3.7"
services:
  wireguard:
    image: linuxserver/wireguard:\${IMAGE_VERSION}
    container_name: wireguard
    hostname: wireguard.$DOMAIN
    domainname: $DOMAIN
    restart: always
    networks:
      federated:
        ipv4_address: 172.99.0.24
    ports:
      - 51820:51820/udp
    volumes:
      - ./data/config:/config
      - ./data/etc/coredns/Corefile:/etc/coredns/Corefile
      - /lib/modules:/lib/modules
    env_file:
      - ./.env
    cap_add:
      - NET_ADMIN
      - SYS_MODULE
    sysctls:
      - net.ipv4.conf.all.src_valid_mark=1

networks:
  federated:
    external: true
EOF

cat > /federated/apps/wireguard/.env <<EOF
IMAGE_VERSION="1.0.20210914"
PUID=1000
PGID=1000
SERVERURL=wireguard.$DOMAIN
SERVERPORT=51820
PEERS=1
PEERDNS=auto
ALLOWEDIPS=0.0.0.0/0,::/0,172.99.0.0/16,192.160.0.0/16,10.13.13.1/32
LOG_CONFS=true
EOF
chmod 600 /federated/apps/wireguard/.env

cat > /federated/apps/wireguard/data/config/coredns/Corefile <<EOF
. {
    hosts {
      172.99.0.13 powerdns.$DOMAIN
      172.99.0.13 traefik.$DOMAIN
      172.99.0.13 panel.$DOMAIN
      172.99.0.13 nextcloud.$DOMAIN
      172.99.0.13 listmonk.$DOMAIN
      172.99.0.13 vaultwarden.$DOMAIN
      172.99.0.13 jitsi.$DOMAIN
      172.99.0.13 element.$DOMAIN
      172.99.0.13 matrix.$DOMAIN
      172.99.0.13 baserow.$DOMAIN
      172.99.0.13 gitea.$DOMAIN
      172.99.0.13 autodiscover.$DOMAIN
      172.99.0.13 castopod.$DOMAIN
      172.99.0.13 wordpress.$DOMAIN
      172.99.0.13 bookstack.$DOMAIN
      172.99.0.13 freescout.$DOMAIN
      172.99.0.13 msp.$DOMAIN
      172.99.0.13 espocrm.$DOMAIN
      fallthrough
    }
    loop
    health
    forward . /etc/resolv.conf
}
EOF
 
kill -9 $SPINPID &> /dev/null
echo -ne "done."
}

start_wireguard() {
  # Start service with command to make sure it's up before proceeding
  start_service "wireguard" "nc -uvz 172.99.0.24 51820 &> /dev/null" "8"

  kill -9 $SPINPID &> /dev/null
  echo -ne "done."
}
