#!/bin/bash 

echo "Clearing old VPN installation..."

LINE=`docker ps --all | grep "hwdsl2/ipsec-vpn-server"`
temp=($LINE)
temp2=${temp[0]}
export username="admin"
export password=`date +%s | sha256sum | base64 | head -c 10`

if [ -z "$temp2" ]
then
    echo "No existing Docker instances found."
else   
    echo "Deleting old VPN container..."
    docker stop $temp2
    docker rm $temp2
fi

echo "Generating env..."

cat <<EOT > vpn.env
VPN_DNS_NAME=$(cat /etc/hostname)
VPN_USER=$username
VPN_IPSEC_PSK=$password
VPN_PASSWORD=$password
EOT

echo "docker run..."

docker run \
    --name ipsec-vpn-server \
    --env-file vpn.env \
    --restart=always \
    -v ikev2-vpn-data:/etc/ipsec.d \
    -v /lib/modules:/lib/modules:ro \
    -p 500:500/udp \
    -p 4500:4500/udp \
    -p 1701:1701/udp \
    -d --privileged \
    hwdsl2/ipsec-vpn-server

echo "Cleaning up..."

rm vpn.env

cat <<EOT > credentials.txt
GENERATED $(date +%s)
VPN_PSKS = $password
VPN_USER = $username
VPN_PASS = $password
EOT
