#!/bin/bash

#
# Name:         wg_regenhtml.sh
# Version:      1.0.1
# Description:  Regenerate WG HTML pages and run accounting script.
#
# (c) 2022-2023, Rapidseedbox, alexey@rapidseedbox.com
#

export PATH=/usr/sbin:/usr/bin:/sbin:/bin

DEBUG="no"
#DEBUG="yes"
export DEBUG


WG_DEV="wg0"
export WG_DEV

_wg_dump="$( wg show wg0 dump )"
export _wg_dump

[ -e "/etc/wireguard/rsb-wg-acct.sh" ] \
    && /bin/bash "/etc/wireguard/rsb-wg-acct.sh"

echo "<html><head><title>RSB: Wireguard information</title><meta http-equiv=\"refresh\" content=\"300\"><meta http-equiv=\"Cache-Control\" content=\"no-cache, no-store, must-revalidate\"/><meta http-equiv=\"Pragma\" content=\"no-cache\"/><meta http-equiv=\"Expires\" content=\"0\"/></head><body><h1>WireGuard</h1>
<h2>Client configurations</h2>
" > "/var/www/html/wireguard/index.html"

while read -r _f ; do
    _num="$( basename "${_f}" | sed -e 's/client-\(.*\)\.conf$/\1/' )"
    _ts="$( date -u '+%s' )"
    _wg_ip="$( awk '$1 == "Address" {print $NF}' "${_f}" | sed -e 's/\/.*$//' )"
    _info_line="$( awk -v ip="${_wg_ip}" \
                          '$4 == ip"/32" && $3 != "51820" && $3 != "(none)" {print $3" "$4" "$5}' \
                         <<< "${_wg_dump}" )"
    read -ra _info_arr <<< "${_info_line}"
    _style=""
    _cc=""
    _connected_ip=""
    _connected_since="${_info_arr[2]}"
    if [ "${_connected_since}" != "0" ] && [ -n "${_info_arr[0]}" ] ; then
        _connected_ip="$( echo "${_info_arr[0]}" | sed -e 's/:.*$//' )"
        _cc="$( whois "${_connected_ip}" | grep -m1 '^country:' | awk '{print $NF}' )"
        _style=" style=\"border:5px double red;\""
    fi
    echo "
<h3>$( basename "${_f}" | sed -e 's/\.conf$//' )$( if [ -n "${_connected_ip}" ] ; then echo ", occupied by: ${_connected_ip}$( [ -n "${_cc}" ] && echo " (${_cc})" ), last seen: $( date -u -d "@${_connected_since}" )" ; fi )</h3>
<pre><code>$( cat "${_f}" )</code></pre>
<img src=\"client-${_num}-qr.png\" alt=\"QR-${_num}\"${_style}>
" >> "/var/www/html/wireguard/index.html"
done < <( find "/var/www/html/wireguard" -mindepth 1 -maxdepth 1 -name "*.conf" | sort )

echo "<br><hr>Genereted on: $( date -u )</body></html>" >> "/var/www/html/wireguard/index.html"

exit 0
