#!/bin/bash

PLAYBOOK="install-support.yml"
INVENTORY="ansible_hosts"

# openvpn_handle is stored in 2 files on disk, one slightly stripped down (from
# the other) due to Ansible.  So we emulate Ansible's behavior, when reading from
# (and later writing to) disk, removing outer cruft as explained on Lines 31-33:
handle1=$(grep "^openvpn_handle:\s" /etc/iiab/local_vars.yml | sed "s/^openvpn_handle:\s\+//; s/#.*//; s/\s*$//; s/^\(['\"]\)\(.*\)\1$/\2/")
# 2021-08-17: bash scripts using default_vars.yml &/or local_vars.yml
# https://github.com/iiab/iiab-factory/blob/master/iiab#L79-L97
# https://github.com/iiab/iiab/blob/master/roles/firmware/templates/iiab-check-firmware#L12
# https://github.com/iiab/iiab/blob/master/roles/network/templates/gateway/iiab-gen-iptables#L47-L51
# https://github.com/iiab/maps/blob/master/osm-source/pages/viewer/scripts/iiab-install-map-region#L25-L34
# https://github.com/iiab/iiab/blob/master/iiab-support READS AND WRITES, INCL NON-BOOLEAN (openvpn_handle)
echo -e "\n/etc/iiab/local_vars.yml source/master copy: $handle1"
if [ -f /etc/iiab/openvpn_handle ]; then
    handle2=$(cat /etc/iiab/openvpn_handle)
    echo -e "/etc/iiab/openvpn_handle for openvpn daemon: $handle2\n"
else
    echo -e "/etc/iiab/openvpn_handle for openvpn daemon: [FILE DOESN'T YET EXIST]\n"
fi

echo -e "\e[1mPlease type a descriptive OpenVPN machine name (openvpn_handle) such as:\n"

echo -e "                     cape-town-school-36-rpi-2019-05-31\n"

echo -en "Or hit [Enter] to keep the existing name:\e[0m "
read ans < /dev/tty

#if [ "$ans" != "" ] || ( [ "$handle1" = "" ] && [ ! -f /etc/iiab/openvpn_handle ] ); then
# -v (below) checks if var's defined: equivalent to file existence test above
if [ "$ans" != "" ] || ( [ "$handle1" = "" ] && [ ! -v handle2 ] ); then
    if grep -q '^openvpn_handle:\s' /etc/iiab/local_vars.yml; then
        sed -i "s/^openvpn_handle:\s.*/openvpn_handle: $ans/" /etc/iiab/local_vars.yml
    else
        echo "openvpn_handle: $ans" >> /etc/iiab/local_vars.yml
    fi

    # BEHAVIOR JUST LIKE ANSIBLE'S: create /etc/iiab/openvpn_handle from the
    # "^openvpn_handle:" line in /etc/iiab/local_vars.yml by (1) removing outer
    # spacing IF NEC, then (2) removing 1 pair of matching outer quotes IF NEC:
    ans=$(echo $ans | sed "s/^\s*//; s/\s*$//; s/^\(['\"]\)\(.*\)\1$/\2/")
    echo $ans > /etc/iiab/openvpn_handle
    echo -e "\n\e[1mSAVED: openvpn_handle recorded into both above files.\e[0m\n"
elif [ "$handle1" != "$handle2" ]; then    # Sloppily, but conveniently here,
    # bash treats "$handle2" as "" when var undefined, catching all conflicts!
    echo -e "\n\e[41mYou MUST specify an OpenVPN machine name (openvpn_handle) to resolve the above\e[0m"
    echo -e "\e[41mnaming conflict. Please rerun to proceed.\e[0m\n"
    exit 1
else
    echo -e "\n\e[1mWARNING: openvpn_handle remains unchanged in both above files.\e[0m\n"
fi

if grep -q '^openvpn_installed:\s\+[tT]rue\b' /etc/iiab/iiab_state.yml; then
    echo -e "Your IIAB installation appears normal, with OpenVPN already installed...\n"
else
    echo -e "Plz wait a few minutes as sshd, iiab-admin & OpenVPN are confirmed/installed...\n"
    if grep -q '^openvpn_install:\s' /etc/iiab/local_vars.yml; then
        sed -i "s/^openvpn_install:\s.*/openvpn_install: True/" /etc/iiab/local_vars.yml
    else
        echo "openvpn_install: True" >> /etc/iiab/local_vars.yml
    fi

    if [ -d /opt/iiab/iiab ]; then
        cd /opt/iiab/iiab
        export ANSIBLE_LOG_PATH="/opt/iiab/iiab/iiab-install.log"
        ansible -m setup -i $INVENTORY localhost --connection=local | grep python
        ansible-playbook -i $INVENTORY $PLAYBOOK --connection=local
        # Above is tighter/better than running all of "./runrole 1-prep"
        echo
    else
        echo -e " \e[41m       Directory /opt/iiab/iiab does not exist: CANNOT INSTALL OPENVPN!       \e[0m\n"
        exit 1
    fi
fi

echo -e "Now let's (re)enable OpenVPN...\n"
if grep -q '^openvpn_enabled:\s' /etc/iiab/local_vars.yml; then
    sed -i "s/^openvpn_enabled:\s.*/openvpn_enabled: True/" /etc/iiab/local_vars.yml
else
    echo "openvpn_enabled: True" >> /etc/iiab/local_vars.yml
fi
systemctl enable openvpn

echo -e "\nNow let's restart OpenVPN..."
#systemctl start openvpn
systemctl restart openvpn

echo -en "\n    "
for i in {16..40} ; do echo -en "\e[48;5;${i}m \e[0m" ; done
echo -en " OpenVPN TIPS "
for i in {40..16} ; do echo -en "\e[48;5;${i}m \e[0m" ; done

echo -e "\n\n  1. Check your Internet connection: run 'ping 8.8.8.8' and 'ping mit.edu'"
echo -e "  2. Check your OpenVPN connection: run 'ping 10.8.0.1'"
echo -e "  3. Run 'ip a' and look for a 'tun0' IP address like 10.8.0.x"
echo -e "  4. If necessary, run 'systemctl restart openvpn' which should"
echo -e "     run 'systemctl restart openvpn@xscenet' for you."
echo -e "  5. SOMETIMES WAITING A MINUTE HELPS -- retry steps 2 and 3 to monitor."
echo -e "  6. If in future you want to disable OpenVPN connections to-and-from your"
echo -e "     Internet-in-a-Box (IIAB) please run 'iiab-support-off' at that time."
echo -e "  7. Read 'How can I remotely manage my Internet-in-a-Box?' at"
echo -e "     http://FAQ.IIAB.IO to learn about DIY remote support alternatives"
echo -e "     like ngrok, serveo, remot3.it and TeamViewer.\n"

echo -en "    "
for i in {16..40} ; do echo -en "\e[48;5;${i}m \e[0m" ; done
echo -en " OpenVPN TIPS "
for i in {40..16} ; do echo -en "\e[48;5;${i}m \e[0m" ; done

echo -e "\n\nNow let's wait 15 seconds, as OpenVPN handshake sometimes needs that (or more!)"
sleep 15

echo -en "\nYour OpenVPN machine name (openvpn_handle) is: \e[32m"
cat /etc/iiab/openvpn_handle
echo -en "\e[0m"

vpnip=$(ip a | grep tun0$ | awk '{print $2}')
if [ "$vpnip" != "" ]; then
    echo -e "\nYour OpenVPN IP address (which can change) is: \e[32m$vpnip\e[0m\n"
else
    echo -e "\n \e[41m       ERROR: OpenVPN IP address not ready - PLEASE TRY THE ABOVE TIPS        \e[0m\n"
    exit 1
fi
