#!/bin/sh

# https://openwrt.org/docs/guide-user/services/vpn/wireguard/extras

# Install packages
opkg update
opkg install luci-proto-wireguard luci-app-wireguard qrencode
/etc/init.d/rpcd restart

# Preserve default route
uci set network.wan.metric="1024"
uci commit network
/etc/init.d/network restart

# Periodically re-resolve inactive peers
cat << "EOF" >> /etc/crontabs/root
* * * * * /usr/bin/wireguard_watchdog
EOF
uci set system.@system[0].cronloglevel="9"
uci commit system
/etc/init.d/cron restart

# Resolve race conditions
cat << "EOF" >> /etc/crontabs/root
* * * * * date -s 2030-01-01; /etc/init.d/sysntpd restart
EOF
uci set system.@system[0].cronloglevel="9"
uci commit system
/etc/init.d/cron restart

# Add route to client side LAN on VPN server.

uci set network.wgclient.route_allowed_ips="1"
uci add_list network.wgclient.allowed_ips="192.168.2.0/24"
uci commit network
/etc/init.d/network restart

# Add route to server side LAN on VPN client.

uci set network.wgserver.route_allowed_ips="1"
uci add_list network.wgserver.allowed_ips="192.168.1.0/24"
uci commit network
/etc/init.d/network restart

# Consider VPN network as private and assign VPN interface to LAN zone on VPN client.

uci del_list firewall.wan.network="vpn"
uci add_list firewall.lan.network="vpn"
uci commit firewall
/etc/init.d/firewall restart


## IPv6 site-to-site
# Add route to client side LAN on VPN server.

uci set network.lan.ip6assign="64"
uci set network.lan.ip6hint="1"
uci set network.vpn.ip6prefix="fdf1:e8a1:8d3f::/48"
uci add_list network.wgclient.allowed_ips="fdf1:e8a1:8d3f:2::/64"
uci commit network
/etc/init.d/network restart

# Add route to server side LAN on VPN client.

uci set network.lan.ip6assign="64"
uci set network.lan.ip6hint="2"
uci set network.vpn.ip6prefix="fdf1:e8a1:8d3f::/48"
uci add_list network.wgserver.allowed_ips="fdf1:e8a1:8d3f:1::/64"
uci commit network
/etc/init.d/network restart
