#!/bin/bash
#
# .---.                  .              .
# |                      |              |
# |--- .--. .-.  .-.  .-.|  .-. .--.--. |.-.  .-. .--.  .-.
# |    |   (.-' (.-' (   | (   )|  |  | |   )(   )|  | (.-'
# '    '     --'  --'  -' -  -' '  '   -' -'   -' '   -  --'
#
#                    Freedom in the Cloud
#
# VPN functions
# https://www.digitalocean.com/community/tutorials/how-to-set-up-an-openvpn-server-on-debian-8
# https://jamielinux.com/blog/force-all-network-traffic-through-openvpn-using-iptables/
# http://www.farrellf.com/projects/software/2016-05-04_Running_a_VPN_Server_with_OpenVPN_and_Stunnel/index_.php
#
# License
# =======
#
# Copyright (C) 2014-2018 Bob Mottram <bob@freedombone.net>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

VARIANTS='full full-vim'

IN_DEFAULT_INSTALL=0
SHOW_ON_ABOUT=0

OPENVPN_SERVER_NAME="server"
OPENVPN_KEY_FILENAME='client.ovpn'

VPN_COUNTRY_CODE="US"
VPN_AREA="Apparent Free Speech Zone"
VPN_LOCATION="Freedomville"
VPN_ORGANISATION="Freedombone"
VPN_UNIT="Freedombone Unit"
STUNNEL_PORT=3439
VPN_TLS_PORT=553
VPN_MESH_TLS_PORT=653

vpn_variables=(MY_EMAIL_ADDRESS
               DEFAULT_DOMAIN_NAME
               MY_USERNAME
               VPN_COUNTRY_CODE
               VPN_AREA
               VPN_LOCATION
               VPN_ORGANISATION
               VPN_UNIT
               VPN_TLS_PORT)

function logging_on_vpn {
    if [ ! -f /etc/openvpn/server.conf ]; then
        return
    fi
    sed -i 's|status .*|status /var/log/openvpn.log|g' /etc/openvpn/server.conf
    systemctl restart openvpn
}

function logging_off_vpn {
    if [ ! -f /etc/openvpn/server.conf ]; then
        return
    fi
    sed -i 's|status .*|status /dev/null|g' /etc/openvpn/server.conf
    systemctl restart openvpn
}

function install_interactive_vpn {
    read_config_param VPN_TLS_PORT
    if [ ! $VPN_TLS_PORT ]; then
        VPN_TLS_PORT=553
    fi
    VPN_DETAILS_COMPLETE=
    while [ ! $VPN_DETAILS_COMPLETE ]
    do
        data=$(tempfile 2>/dev/null)
        trap "rm -f $data" 0 1 2 5 15
        currtlsport=$(grep 'VPN_TLS_PORT' temp.cfg | awk -F '=' '{print $2}')
        if [ $currtlsport ]; then
            VPN_TLS_PORT=$currtlsport
        fi
        dialog --backtitle $"Freedombone Configuration" \
               --title $"VPN Configuration" \
               --form $"\nPlease enter your VPN details. Changing the port to 443 will help defend against censorship but will prevent other web apps from running." 12 65 1 \
               $"TLS port:" 1 1 "$VPN_TLS_PORT" 1 12 5 5 \
               2> $data
        sel=$?
        case $sel in
            1) exit 1;;
            255) exit 1;;
        esac
        tlsport=$(cat $data | sed -n 1p)
        if [ ${#tlsport} -gt 1 ]; then
            if [[ "$tlsport" != *' '* && "$tlsport" != *'.'* ]]; then
                VPN_TLS_PORT="$tlsport"
                VPN_DETAILS_COMPLETE="yes"
                write_config_param "VPN_TLS_PORT" "$VPN_TLS_PORT"
            fi
        fi
    done
    clear
    APP_INSTALLED=1
}

function vpn_change_tls_port {
    if ! grep -q "VPN-TLS" $FIREWALL_CONFIG; then
        EXISTING_VPN_TLS_PORT=443
    else
        EXISTING_VPN_TLS_PORT=$(cat $FIREWALL_CONFIG | grep "VPN-TLS" | awk -F '=' '{print $2}')
    fi

    data=$(tempfile 2>/dev/null)
    trap "rm -f $data" 0 1 2 5 15
    dialog --title $"VPN Configuration" \
           --backtitle $"Freedombone Control Panel" \
           --inputbox $'Change TLS port' 10 50 $EXISTING_VPN_TLS_PORT 2>$data
    sel=$?
    case $sel in
        0)
            tlsport=$(<$data)
            if [ ${#tlsport} -gt 0 ]; then
                if [[ "$tlsport" != "$EXISTING_VPN_TLS_PORT" ]]; then
                    clear
                    VPN_TLS_PORT=$tlsport
                    write_config_param "VPN_TLS_PORT" "$VPN_TLS_PORT"
                    sed -i "s|accept =.*|accept = $VPN_TLS_PORT|g" /etc/stunnel/stunnel.conf
                    sed -i "s|connect =.*|connect = :$VPN_TLS_PORT|g" /etc/stunnel/stunnel-client.conf

                    for d in /home/*/ ; do
                        USERNAME=$(echo "$d" | awk -F '/' '{print $3}')
                        if [ -f /home/$USERNAME/stunnel-client.conf ]; then
                            cp /etc/stunnel/stunnel-client.conf /home/$USERNAME/stunnel-client.conf
                            chown $USERNAME:$USERNAME /home/$USERNAME/stunnel-client.conf
                        fi
                    done

                    if [ $VPN_TLS_PORT -eq 443 ]; then
                        if [[ "$PREVIOUS_VPN_TLS_PORT" != "443" ]]; then
                            firewall_remove VPN-TLS ${EXISTING_VPN_TLS_PORT}
                        fi
                        systemctl stop nginx
                        systemctl disable nginx
                    else
                        if [[ "$PREVIOUS_VPN_TLS_PORT" != "$VPN_TLS_PORT" ]]; then
                            firewall_remove VPN-TLS ${EXISTING_VPN_TLS_PORT}
                            firewall_add VPN-TLS ${VPN_TLS_PORT} tcp
                        fi
                        systemctl enable nginx
                        systemctl restart nginx
                    fi

                    systemctl restart stunnel

                    if [ $VPN_TLS_PORT -eq 443 ]; then
                        dialog --title $"VPN Configuration" \
                               --msgbox $"TLS port changed to ${VPN_TLS_PORT}. Forward this port from your internet router." 10 60
                    else
                        dialog --title $"VPN Configuration" \
                               --msgbox $"TLS port changed to ${VPN_TLS_PORT}. Forward this port from your internet router." 10 60
                    fi
                fi
            fi
            ;;
    esac
}

function vpn_regenerate_client_keys {
    data=$(tempfile 2>/dev/null)
    trap "rm -f $data" 0 1 2 5 15
    dialog --title $"Regenerate VPN keys for a user" \
           --backtitle $"Freedombone Control Panel" \
           --inputbox $'username' 10 50 2>$data
    sel=$?
    case $sel in
        0)
            USERNAME=$(<$data)
            if [ ${#USERNAME} -gt 0 ]; then
                if [ -d /home/$USERNAME ]; then
                    clear
                    create_user_vpn_key $USERNAME
                    dialog --title $"Regenerate VPN keys for a user" \
                           --msgbox $"VPN keys were regenerated for $USERNAME" 6 60
                fi
            fi
            ;;
    esac
}

function configure_interactive_vpn {
    read_config_param VPN_TLS_PORT
    while true
    do
        data=$(tempfile 2>/dev/null)
        trap "rm -f $data" 0 1 2 5 15
        dialog --backtitle $"Freedombone Control Panel" \
               --title $"VPN Configuration" \
               --radiolist $"Choose an operation:" 13 70 3 \
               1 $"Change TLS port (currently $VPN_TLS_PORT)" off \
               2 $"Regenerate keys for a user" off \
               3 $"Exit" on 2> $data
        sel=$?
        case $sel in
            1) return;;
            255) return;;
        esac
        case $(cat $data) in
            1) vpn_change_tls_port;;
            2) vpn_regenerate_client_keys;;
            3) break;;
        esac
    done
}

function reconfigure_vpn {
    echo -n ''
}

function upgrade_vpn {
    echo -n ''
}

function backup_local_vpn {
    for d in /home/*/ ; do
        USERNAME=$(echo "$d" | awk -F '/' '{print $3}')
        if [ -f /home/$USERNAME/$OPENVPN_KEY_FILENAME ]; then
            cp /home/$USERNAME/$OPENVPN_KEY_FILENAME /etc/openvpn/easy-rsa/keys/${USERNAME}_${OPENVPN_KEY_FILENAME}
        fi
    done

    function_check backup_directory_to_usb
    backup_directory_to_usb /etc/openvpn/easy-rsa/keys vpn
    backup_directory_to_usb /etc/stunnel vpnstunnel
}

function restore_local_vpn {
    temp_restore_dir=/root/tempvpn
    restore_directory_from_usb $temp_restore_dir vpn
    if [ -d ${temp_restore_dir} ]; then
        cp -r ${temp_restore_dir}/* /etc/openvpn/easy-rsa/keys
        cp -r ${temp_restore_dir}/${OPENVPN_SERVER_NAME}* /etc/openvpn/
        cp -r ${temp_restore_dir}/dh* /etc/openvpn/
        rm -rf ${temp_restore_dir}

        for d in /home/*/ ; do
            USERNAME=$(echo "$d" | awk -F '/' '{print $3}')
            if [ -f /etc/openvpn/easy-rsa/keys/${USERNAME}_${OPENVPN_KEY_FILENAME} ]; then
                cp /etc/openvpn/easy-rsa/keys/${USERNAME}_${OPENVPN_KEY_FILENAME} /home/$USERNAME/$OPENVPN_KEY_FILENAME
                chown $USERNAME:$USERNAME /home/$USERNAME/$OPENVPN_KEY_FILENAME
            fi
        done
    fi
    temp_restore_dir=/root/tempvpnstunnel
    restore_directory_from_usb $temp_restore_dir vpnstunnel
    if [ -d ${temp_restore_dir} ]; then
        cp -r ${temp_restore_dir}/* /etc/stunnel
        rm -rf ${temp_restore_dir}
        for d in /home/*/ ; do
            USERNAME=$(echo "$d" | awk -F '/' '{print $3}')
            if [ -f /home/$USERNAME/stunnel.pem ]; then
                cp /etc/stunnel/stunnel.pem /home/$USERNAME/stunnel.pem
                chown $USERNAME:$USERNAME /home/$USERNAME/stunnel.pem
            fi
            if [ -f /home/$USERNAME/stunnel.p12 ]; then
                cp /etc/stunnel/stunnel.p12 /home/$USERNAME/stunnel.p12
                chown $USERNAME:$USERNAME /home/$USERNAME/stunnel.p12
            fi
        done
    fi
}

function backup_remote_vpn {
    for d in /home/*/ ; do
        USERNAME=$(echo "$d" | awk -F '/' '{print $3}')
        if [ -f /home/$USERNAME/$OPENVPN_KEY_FILENAME ]; then
            cp /home/$USERNAME/$OPENVPN_KEY_FILENAME /etc/openvpn/easy-rsa/keys/${USERNAME}_${OPENVPN_KEY_FILENAME}
        fi
    done

    function_check backup_directory_to_friend
    backup_directory_to_friend /etc/openvpn/easy-rsa/keys vpn
    backup_directory_to_friend /etc/stunnel vpnstunnel
}

function restore_remote_vpn {
    temp_restore_dir=/root/tempvpn
    restore_directory_from_friend $temp_restore_dir vpn
    if [ -d ${temp_restore_dir} ]; then
        cp -r ${temp_restore_dir}/* /etc/openvpn/easy-rsa/keys
        cp -r ${temp_restore_dir}/${OPENVPN_SERVER_NAME}* /etc/openvpn/
        cp -r ${temp_restore_dir}/dh* /etc/openvpn/
        rm -rf ${temp_restore_dir}

        for d in /home/*/ ; do
            USERNAME=$(echo "$d" | awk -F '/' '{print $3}')
            if [ -f /etc/openvpn/easy-rsa/keys/${USERNAME}_${OPENVPN_KEY_FILENAME} ]; then
                cp /etc/openvpn/easy-rsa/keys/${USERNAME}_${OPENVPN_KEY_FILENAME} /home/$USERNAME/$OPENVPN_KEY_FILENAME
                chown $USERNAME:$USERNAME /home/$USERNAME/$OPENVPN_KEY_FILENAME
            fi
        done
    fi
    temp_restore_dir=/root/tempvpnstunnel
    restore_directory_from_friend $temp_restore_dir vpnstunnel
    if [ -d ${temp_restore_dir} ]; then
        cp -r ${temp_restore_dir}/* /etc/stunnel
        rm -rf ${temp_restore_dir}
        for d in /home/*/ ; do
            USERNAME=$(echo "$d" | awk -F '/' '{print $3}')
            if [ -f /home/$USERNAME/stunnel.pem ]; then
                cp /etc/stunnel/stunnel.pem /home/$USERNAME/stunnel.pem
                chown $USERNAME:$USERNAME /home/$USERNAME/stunnel.pem
            fi
            if [ -f /home/$USERNAME/stunnel.p12 ]; then
                cp /etc/stunnel/stunnel.p12 /home/$USERNAME/stunnel.p12
                chown $USERNAME:$USERNAME /home/$USERNAME/stunnel.p12
            fi
        done
    fi
}

function remove_vpn {
    systemctl stop stunnel
    systemctl disable stunnel
    rm /etc/systemd/system/stunnel.service

    systemctl stop openvpn
    if [ $VPN_TLS_PORT -ne 443 ]; then
        firewall_remove VPN-TLS $VPN_TLS_PORT
    else
        systemctl enable nginx
        systemctl restart nginx
    fi

    apt-get -yq remove --purge fastd openvpn easy-rsa
    apt-get -yq remove stunnel4
    if [ -d /etc/openvpn ]; then
        rm -rf /etc/openvpn
    fi
    firewall_disable_vpn

    echo 0 > /proc/sys/net/ipv4/ip_forward
    sed -i 's|net.ipv4.ip_forward=.*|net.ipv4.ip_forward=0|g' /etc/sysctl.conf

    remove_completion_param install_vpn

    # remove any client keys
    for d in /home/*/ ; do
        USERNAME=$(echo "$d" | awk -F '/' '{print $3}')
        if [ -f /home/$USERNAME/$OPENVPN_KEY_FILENAME ]; then
            shred -zu /home/$USERNAME/$OPENVPN_KEY_FILENAME
        fi
        rm /home/$USERNAME/stunnel*
    done
    userdel -f vpn
    groupdel -f vpn

    if [ -d /etc/stunnel ]; then
        rm -rf /etc/stunnel
    fi
}

function create_user_vpn_key {
    username=$1

    if [ ! -d /home/$username ]; then
        return
    fi

    echo $"Creating VPN key for $username"

    cd /etc/openvpn/easy-rsa

    if [ -f /etc/openvpn/easy-rsa/keys/$username.crt ]; then
        rm /etc/openvpn/easy-rsa/keys/$username.crt
    fi
    if [ -f /etc/openvpn/easy-rsa/keys/$username.key ]; then
        rm /etc/openvpn/easy-rsa/keys/$username.key
    fi
    if [ -f /etc/openvpn/easy-rsa/keys/$username.csr ]; then
        rm /etc/openvpn/easy-rsa/keys/$username.csr
    fi

    sed -i 's| --interact||g' build-key
    ./build-key "$username"

    if [ ! -f /etc/openvpn/easy-rsa/keys/$username.crt ]; then
        echo $'VPN user cert not generated'
        exit 783528
    fi
    user_cert=$(cat /etc/openvpn/easy-rsa/keys/$username.crt)
    if [ ${#user_cert} -lt 10 ]; then
        cat /etc/openvpn/easy-rsa/keys/$username.crt
        echo $'User cert generation failed'
        exit 634659
    fi
    if [ ! -f /etc/openvpn/easy-rsa/keys/$username.key ]; then
        echo $'VPN user key not generated'
        exit 682523
    fi
    user_key=$(cat /etc/openvpn/easy-rsa/keys/$username.key)
    if [ ${#user_key} -lt 10 ]; then
        cat /etc/openvpn/easy-rsa/keys/$username.key
        echo $'User key generation failed'
        exit 285838
    fi

    user_vpn_cert_file=/home/$username/$OPENVPN_KEY_FILENAME

    echo 'client' > $user_vpn_cert_file
    echo 'dev tun' >> $user_vpn_cert_file
    echo 'proto tcp' >> $user_vpn_cert_file
    echo "remote localhost $STUNNEL_PORT" >> $user_vpn_cert_file
    echo "route $DEFAULT_DOMAIN_NAME 255.255.255.255 net_gateway" >> $user_vpn_cert_file
    echo 'resolv-retry infinite' >> $user_vpn_cert_file
    echo 'nobind' >> $user_vpn_cert_file
    echo 'tun-mtu 1500' >> $user_vpn_cert_file
    echo 'tun-mtu-extra 32' >> $user_vpn_cert_file
    echo 'mssfix 1450' >> $user_vpn_cert_file
    echo 'persist-key' >> $user_vpn_cert_file
    echo 'persist-tun' >> $user_vpn_cert_file
    echo 'auth-nocache' >> $user_vpn_cert_file
    echo 'remote-cert-tls server' >> $user_vpn_cert_file
    echo 'comp-lzo' >> $user_vpn_cert_file
    echo 'verb 3' >> $user_vpn_cert_file
    echo '' >> $user_vpn_cert_file

    echo '<ca>' >> $user_vpn_cert_file
    cat /etc/openvpn/ca.crt >> $user_vpn_cert_file
    echo '</ca>' >> $user_vpn_cert_file

    echo '<cert>' >> $user_vpn_cert_file
    cat /etc/openvpn/easy-rsa/keys/$username.crt >> $user_vpn_cert_file
    echo '</cert>' >> $user_vpn_cert_file

    echo '<key>' >> $user_vpn_cert_file
    cat /etc/openvpn/easy-rsa/keys/$username.key >> $user_vpn_cert_file
    echo '</key>' >> $user_vpn_cert_file

    chown $username:$username $user_vpn_cert_file

    # keep a backup
    cp $user_vpn_cert_file /etc/openvpn/easy-rsa/keys/$username.ovpn

    #rm /etc/openvpn/easy-rsa/keys/$username.crt
    #rm /etc/openvpn/easy-rsa/keys/$username.csr
    shred -zu /etc/openvpn/easy-rsa/keys/$username.key

    echo $"VPN key created at $user_vpn_cert_file"
}

function add_user_vpn {
    new_username="$1"
    new_user_password="$2"

    create_user_vpn_key $new_username
    if [ -f /etc/stunnel/stunnel.pem ]; then
        cp /etc/stunnel/stunnel.pem /home/$new_username/stunnel.pem
        chown $new_username:$new_username /home/$new_username/stunnel.pem
    fi
    if [ -f /etc/stunnel/stunnel.p12 ]; then
        cp /etc/stunnel/stunnel.p12 /home/$new_username/stunnel.p12
        chown $new_username:$new_username /home/$new_username/stunnel.p12
    fi
    cp /etc/stunnel/stunnel-client.conf /home/$new_username/stunnel-client.conf
    chown $new_username:$new_username /home/$new_username/stunnel-client.conf
}

function remove_user_vpn {
    new_username="$1"
}

function mesh_setup_vpn {
    vpn_generate_keys

    if [ -d /home/fbone ]; then
        cp /etc/stunnel/stunnel-client.conf /home/fbone/stunnel-client.conf
        chown fbone:fbone /home/fbone/stunnel*
    fi

    generate_stunnel_keys

    systemctl restart openvpn
}

function generate_stunnel_keys {
    openssl req -x509 -nodes -days 3650 -sha256 \
            -subj "/O=$VPN_ORGANISATION/OU=$VPN_UNIT/C=$VPN_COUNTRY_CODE/ST=$VPN_AREA/L=$VPN_LOCATION/CN=$HOSTNAME" \
            -newkey rsa:2048 -keyout /etc/stunnel/key.pem \
            -out /etc/stunnel/cert.pem
    if [ ! -f /etc/stunnel/key.pem ]; then
        echo $'stunnel key not created'
        exit 793530
    fi
    if [ ! -f /etc/stunnel/cert.pem ]; then
        echo $'stunnel cert not created'
        exit 204587
    fi
    chmod 400 /etc/stunnel/key.pem
    chmod 640 /etc/stunnel/cert.pem

    cat /etc/stunnel/key.pem /etc/stunnel/cert.pem >> /etc/stunnel/stunnel.pem
    chmod 640 /etc/stunnel/stunnel.pem

    openssl pkcs12 -export -out /etc/stunnel/stunnel.p12 -inkey /etc/stunnel/key.pem -in /etc/stunnel/cert.pem -passout pass:
    if [ ! -f /etc/stunnel/stunnel.p12 ]; then
        echo $'stunnel pkcs12 not created'
        exit 639353
    fi
    chmod 640 /etc/stunnel/stunnel.p12

    cp /etc/stunnel/stunnel.pem /home/$MY_USERNAME/stunnel.pem
    cp /etc/stunnel/stunnel.p12 /home/$MY_USERNAME/stunnel.p12
    chown $MY_USERNAME:$MY_USERNAME $prefix$userhome/stunnel*
}

function install_stunnel {
    prefix=
    prefixchroot=
    if [ $rootdir ]; then
        prefix=$rootdir
        prefixchroot="chroot $rootdir"
        VPN_TLS_PORT=$VPN_MESH_TLS_PORT
    fi

    $prefixchroot apt-get -yq install stunnel4

    if [ ! $prefix ]; then
        cd /etc/stunnel
        generate_stunnel_keys
    fi

    echo 'chroot = /var/lib/stunnel4' > $prefix/etc/stunnel/stunnel.conf
    echo 'pid = /stunnel4.pid' >> $prefix/etc/stunnel/stunnel.conf
    echo 'setuid = stunnel4' >> $prefix/etc/stunnel/stunnel.conf
    echo 'setgid = stunnel4' >> $prefix/etc/stunnel/stunnel.conf
    echo 'socket = l:TCP_NODELAY=1' >> $prefix/etc/stunnel/stunnel.conf
    echo 'socket = r:TCP_NODELAY=1' >> $prefix/etc/stunnel/stunnel.conf
    echo 'cert = /etc/stunnel/stunnel.pem' >> $prefix/etc/stunnel/stunnel.conf
    echo '[openvpn]' >> $prefix/etc/stunnel/stunnel.conf
    echo "accept = $VPN_TLS_PORT" >> $prefix/etc/stunnel/stunnel.conf
    echo 'connect = localhost:1194' >> $prefix/etc/stunnel/stunnel.conf
    echo 'cert = /etc/stunnel/stunnel.pem' >> $prefix/etc/stunnel/stunnel.conf
    echo 'protocol = socks' >> $prefix/etc/stunnel/stunnel.conf

    sed -i 's|ENABLED=.*|ENABLED=1|g' $prefix/etc/default/stunnel4

    echo '[openvpn]' > $prefix/etc/stunnel/stunnel-client.conf
    echo 'client = yes' >> $prefix/etc/stunnel/stunnel-client.conf
    echo "accept = $STUNNEL_PORT" >> $prefix/etc/stunnel/stunnel-client.conf
    echo "connect = $DEFAULT_DOMAIN_NAME:$VPN_TLS_PORT" >> $prefix/etc/stunnel/stunnel-client.conf
    echo 'cert = stunnel.pem' >> $prefix/etc/stunnel/stunnel-client.conf
    echo 'protocol = socks' >> $prefix/etc/stunnel/stunnel-client.conf

    echo '[Unit]' > $prefix/etc/systemd/system/stunnel.service
    echo 'Description=SSL tunnel for network daemons' >> $prefix/etc/systemd/system/stunnel.service
    echo 'Documentation=man:stunnel https://www.stunnel.org/docs.html' >> $prefix/etc/systemd/system/stunnel.service
    echo 'DefaultDependencies=no' >> $prefix/etc/systemd/system/stunnel.service
    echo 'After=network.target' >> $prefix/etc/systemd/system/stunnel.service
    echo 'After=syslog.target' >> $prefix/etc/systemd/system/stunnel.service
    echo '' >> $prefix/etc/systemd/system/stunnel.service
    echo '[Install]' >> $prefix/etc/systemd/system/stunnel.service
    echo 'WantedBy=multi-user.target' >> $prefix/etc/systemd/system/stunnel.service
    echo 'Alias=stunnel.target' >> $prefix/etc/systemd/system/stunnel.service
    echo '' >> $prefix/etc/systemd/system/stunnel.service
    echo '[Service]' >> $prefix/etc/systemd/system/stunnel.service
    echo 'Type=forking' >> $prefix/etc/systemd/system/stunnel.service
    echo 'RuntimeDirectory=stunnel' >> $prefix/etc/systemd/system/stunnel.service
    echo 'EnvironmentFile=-/etc/stunnel/stunnel.conf' >> $prefix/etc/systemd/system/stunnel.service
    echo 'ExecStart=/usr/bin/stunnel /etc/stunnel/stunnel.conf' >> $prefix/etc/systemd/system/stunnel.service
    echo 'ExecStop=/usr/bin/killall -9 stunnel' >> $prefix/etc/systemd/system/stunnel.service
    echo 'RemainAfterExit=yes' >> $prefix/etc/systemd/system/stunnel.service

    if [ ! $prefix ]; then
        if [ $VPN_TLS_PORT -eq 443 ]; then
            systemctl stop nginx
            systemctl disable nginx
        else
            systemctl enable nginx
            systemctl restart nginx
        fi

        systemctl enable stunnel
        systemctl daemon-reload
        systemctl start stunnel

        cp /etc/stunnel/stunnel-client.conf /home/$MY_USERNAME/stunnel-client.conf
        chown $MY_USERNAME:$MY_USERNAME /home/$MY_USERNAME/stunnel*
    fi
}

function vpn_generate_keys {
    # generate host keys
    if [ ! -f /etc/openvpn/dh2048.pem ]; then
        ${PROJECT_NAME}-dhparam -o /etc/openvpn/dh2048.pem
    fi
    if [ ! -f /etc/openvpn/dh2048.pem ]; then
        echo $'vpn dhparams were not generated'
        exit 73724523
    fi
    cp /etc/openvpn/dh2048.pem /etc/openvpn/easy-rsa/keys/dh2048.pem

    cd /etc/openvpn/easy-rsa
    . ./vars
    ./clean-all
    vpn_openssl_version='1.0.0'
    if [ ! -f openssl-${vpn_openssl_version}.cnf ]; then
        echo $"openssl-${vpn_openssl_version}.cnf was not found"
        exit 7392353
    fi
    cp openssl-${vpn_openssl_version}.cnf openssl.cnf

    if [ -f /etc/openvpn/easy-rsa/keys/${OPENVPN_SERVER_NAME}.crt ]; then
        rm /etc/openvpn/easy-rsa/keys/${OPENVPN_SERVER_NAME}.crt
    fi
    if [ -f /etc/openvpn/easy-rsa/keys/${OPENVPN_SERVER_NAME}.key ]; then
        rm /etc/openvpn/easy-rsa/keys/${OPENVPN_SERVER_NAME}.key
    fi
    if [ -f /etc/openvpn/easy-rsa/keys/${OPENVPN_SERVER_NAME}.csr ]; then
        rm /etc/openvpn/easy-rsa/keys/${OPENVPN_SERVER_NAME}.csr
    fi
    sed -i 's| --interact||g' build-key-server
    sed -i 's| --interact||g' build-ca
    ./build-ca
    ./build-key-server ${OPENVPN_SERVER_NAME}
    if [ ! -f /etc/openvpn/easy-rsa/keys/${OPENVPN_SERVER_NAME}.crt ]; then
        echo $'OpenVPN crt not found'
        exit 7823352
    fi
    server_cert=$(cat /etc/openvpn/easy-rsa/keys/${OPENVPN_SERVER_NAME}.crt)
    if [ ${#server_cert} -lt 10 ]; then
        cat /etc/openvpn/easy-rsa/keys/${OPENVPN_SERVER_NAME}.crt
        echo $'Server cert generation failed'
        exit 3284682
    fi

    if [ ! -f /etc/openvpn/easy-rsa/keys/${OPENVPN_SERVER_NAME}.key ]; then
        echo $'OpenVPN key not found'
        exit 6839436
    fi
    if [ ! -f /etc/openvpn/easy-rsa/keys/ca.key ]; then
        echo $'OpenVPN ca not found'
        exit 7935203
    fi
    cp /etc/openvpn/easy-rsa/keys/{$OPENVPN_SERVER_NAME.crt,$OPENVPN_SERVER_NAME.key,ca.crt} /etc/openvpn

    create_user_vpn_key ${MY_USERNAME}
}

function install_vpn {
    prefix=
    prefixchroot=
    if [ $rootdir ]; then
        prefix=$rootdir
        prefixchroot="chroot $rootdir"
        VPN_TLS_PORT=$VPN_MESH_TLS_PORT
    fi
    $prefixchroot apt-get -yq install fastd openvpn easy-rsa

    $prefixchroot groupadd vpn
    $prefixchroot useradd -r -s /bin/false -g vpn vpn

    # server configuration
    echo 'port 1194' > $prefix/etc/openvpn/server.conf
    echo 'proto tcp' >> $prefix/etc/openvpn/server.conf
    echo 'dev tun' >> $prefix/etc/openvpn/server.conf
    echo 'tun-mtu 1500' >> $prefix/etc/openvpn/server.conf
    echo 'tun-mtu-extra 32' >> $prefix/etc/openvpn/server.conf
    echo 'mssfix 1450' >> $prefix/etc/openvpn/server.conf
    echo 'ca /etc/openvpn/ca.crt' >> $prefix/etc/openvpn/server.conf
    echo 'cert /etc/openvpn/server.crt' >> $prefix/etc/openvpn/server.conf
    echo 'key /etc/openvpn/server.key' >> $prefix/etc/openvpn/server.conf
    echo 'dh /etc/openvpn/dh2048.pem' >> $prefix/etc/openvpn/server.conf
    echo 'server 10.8.0.0 255.255.255.0' >> $prefix/etc/openvpn/server.conf
    echo 'push "redirect-gateway def1 bypass-dhcp"' >> $prefix/etc/openvpn/server.conf
    echo "push \"dhcp-option DNS 85.214.73.63\"" >> $prefix/etc/openvpn/server.conf
    echo "push \"dhcp-option DNS 213.73.91.35\"" >> $prefix/etc/openvpn/server.conf
    echo 'keepalive 5 30' >> $prefix/etc/openvpn/server.conf
    echo 'comp-lzo' >> $prefix/etc/openvpn/server.conf
    echo 'persist-key' >> $prefix/etc/openvpn/server.conf
    echo 'persist-tun' >> $prefix/etc/openvpn/server.conf
    echo 'status /dev/null' >> $prefix/etc/openvpn/server.conf
    echo 'verb 3' >> $prefix/etc/openvpn/server.conf
    echo '' >> $prefix/etc/openvpn/server.conf

    if [ ! $prefix ]; then
        echo 1 > /proc/sys/net/ipv4/ip_forward
    fi
    sed -i 's|# net.ipv4.ip_forward|net.ipv4.ip_forward|g' $prefix/etc/sysctl.conf
    sed -i 's|#net.ipv4.ip_forward|net.ipv4.ip_forward|g' $prefix/etc/sysctl.conf
    sed -i 's|net.ipv4.ip_forward.*|net.ipv4.ip_forward=1|g' $prefix/etc/sysctl.conf

    cp -r $prefix/usr/share/easy-rsa/ $prefix/etc/openvpn
    if [ ! -d $prefix/etc/openvpn/easy-rsa/keys ]; then
        mkdir $prefix/etc/openvpn/easy-rsa/keys
    fi

    # keys configuration
    sed -i "s|export KEY_COUNTRY.*|export KEY_COUNTRY=\"US\"|g" $prefix/etc/openvpn/easy-rsa/vars
    sed -i "s|export KEY_PROVINCE.*|export KEY_PROVINCE=\"TX\"|g" $prefix/etc/openvpn/easy-rsa/vars
    sed -i "s|export KEY_CITY.*|export KEY_CITY=\"Dallas\"|g" $prefix/etc/openvpn/easy-rsa/vars
    sed -i "s|export KEY_ORG.*|export KEY_ORG=\"$PROJECT_NAME\"|g" $prefix/etc/openvpn/easy-rsa/vars
    sed -i "s|export KEY_EMAIL.*|export KEY_EMAIL=\"$MY_EMAIL_ADDRESS\"|g" $prefix/etc/openvpn/easy-rsa/vars
    sed -i "s|export KEY_OU=.*|export KEY_OU=\"MoonUnit\"|g" $prefix/etc/openvpn/easy-rsa/vars
    sed -i "s|export KEY_NAME.*|export KEY_NAME=\"$OPENVPN_SERVER_NAME\"|g" $prefix/etc/openvpn/easy-rsa/vars

    if [ ! $prefix ]; then
        vpn_generate_keys
        firewall_enable_vpn

        if [ ${VPN_TLS_PORT} -ne 443 ]; then
            firewall_add VPN-TLS ${VPN_TLS_PORT} tcp
        fi

        systemctl start openvpn
    fi

    install_stunnel

    if [ ! $prefix ]; then
        systemctl restart openvpn
    fi

    APP_INSTALLED=1
}

# NOTE: deliberately there is no "exit 0"
