#!/bin/bash

# -i to setup new wireguard client

#{

LOGFILE=/tmp/rem_gui_wg.log
BASEDIR=/opt/euro-beta
WG_IFACE=wg0
WG_CONFIG="/etc/wireguard/${WG_IFACE}.conf"
WG_SERVICE="wg-quick@${WG_IFACE}.service"

VIRTUAL_APPLIANCE=0


if [ "$1" = "-i" ]; then
  INSTALL=1
fi

LOCKFILE=/var/lock/`basename $0`
TMPLOCK=/tmp/`basename $0`.$$

cd $BASEDIR

if [ -f /opt/euro-beta/e3g_setup_appliance ]
then
  VIRTUAL_APPLIANCE=1
  SPINKEY_ERR=0
  SPINKEY_SERNR=0
else
  SPINKEY_ERR=`./systools/get_eurodb_config_val SpinKeyError`
  SPINKEY_SERNR=`./systools/get_eurodb_config_val SpinKeySerNr`

fi

if [ "$SPINKEY_ERR" -ne 0 ]
then
  if [ -f $WG_CONFIG ]
  then
    systemctl stop $WG_SERVICE
  fi
else
  if [ "$INSTALL" -eq 1 ]
  then

    echo -n "Enter Remote Setup CustomerID ( 1 - 1024 ) : "
    read CUST_ID
    echo -n "Enter Station IDX in remote pool ( 1 - 11 ) : "
    read STATION_ID
    STATION_IP="10.20.$(($CUST_ID/16)).$((16*($CUST_ID%16)+$STATION_ID))"

    wg genkey | tee wg-private.key | wg pubkey > wg-public.key
    WG_PRIVATE_KEY=`cat wg-private.key`
    WG_PUBLIC_KEY=`cat wg-public.key`


    cat > $WG_CONFIG <<EOF
## SpinKeyNr=$SPINKEY_SERNR
[Interface]
Address = $STATION_IP/28
ListenPort = 51828
PrivateKey = $WG_PRIVATE_KEY

[Peer]
PublicKey = ARaExLE1o8Ce2nmoX25tWIFDfjyS+4JgrXbHIKITZDI=
AllowedIPs = 10.20.1.0/28, 10.20.0.1/32
Endpoint = 167.86.70.166:51828
PersistentKeepalive = 25

EOF
    WG_PRIVATE_KEY=`cat wg-private.key | sed 's|/|\\\\/|g; s|*|\\\\*|g; s|+|\\\\+|g'`

    REAL_URL=`curl -Ls -o /dev/null -w %{url_effective} https://e3g.spintec.com/e3g_services/remote_setup/regist.php`
    curl --data-urlencode id="Customer $CUST_ID, Station idx $STATION_ID" --data-urlencode text="SpinKey: $SPINKEY_SERNR , Key: $WG_PUBLIC_KEY , IP: $STATION_IP" $REAL_URL >> $LOGFILE 2>&1
    rm wg-private.key
    rm wg-public.key
  else
    if [ -f $WG_CONFIG ]
    then
      if grep -q "## SpinKeyNr=$SPINKEY_SERNR" $WG_CONFIG 
      then
        if ! systemctl is-active $WG_SERVICE >/dev/null
        then 
          systemctl start $WG_SERVICE
        fi
      else
        systemctl stop $WG_SERVICE
      fi
    fi
  fi
fi
exit 0

#} >>$LOGFILE 2>&1


