#!/bin/bash
#
# Displays a snapshot of the current openvpn server session
# Including 4 secs of bandwidth monitoring

function Usage () {
    echo "Displays a snapshot of the current openvpn server session.
Including 4 secs of bandwidth monitoring.
For watching, its probably best to use 'watch ovs status'.
"
}


function Open_Table_Section() {
    echo "
    <tbody>
    <tr>
        <th colspan=4>$server_conf</th>
    </tr>
    "
}

function Create_Table_Row() {
    echo "
    <tr class=\"$row_class\">
        <td>$vpn_name</td>
        <td>$vpn_ip</td>
        <td>$public_ip</td>
        <td>$connected_since</td>
    </tr>
    "
}

function Close_Table_Section {
    echo "
    </tbody>
    "
}

# Create a openvpn connection status web page, shows all vpn connections based on valid keys and CCD settings
#
# USAGE: Create connect and disconnect scripts and add the lines to the server conf file to automatically call
#       this script when clients connect and disconnect
#   client-connect /etc/openvpn/connect
#   client-disconnect /etc/openvpn/disconnect

# /etc/openvpn/connect
##!/bin/bash
##Connect script
#ovs status --connect &
#return 0

# /etc/openvpn/disconnect
##!/bin/bash
## Disconnect script
#ovs status --disconnect &
#return 0

function Create_Html_Status() {

    rm /tmp/vpnstatus_*.html 2>&1

    local template_html="/usr/share/openvpn-server/config-templates/status.html"
    local tmp_html="/tmp/vpnstatus_$$.html"
    local connected_user=""

    #If this is blank the temp file isn't copied anywhere
    #local live_html="/var/www/vpn/status.html"
    local live_html=""

    # These variables come from openvpn and the connection that is currently being made
    local this_vpnname=$common_name
    local this_ip=$trusted_ip

    # give the the status log time to come up (needed on restart with multiple clients)...
    # I'm not sure this is a good idea, it appears this script needs to execute before connection completes
    if [ $connection_type == "connect" ]; then
        sleep 30
    fi

    if [ "$connection_type" == "connect" ] || [ "$connection_type" == "disconnect" ]; then
        generated_details="<p>The most recent user was $this_vpnname who "`echo '$connection_type' | sed -e "s/-//g"`"ed from $public_ip at "`date`".<\/p>"
    else
        generated_details="<p>Generated on `date`.<\/p>"

    fi

    server_conf=""
    #TODO: Can we do some fancy read each conf an list keys for that conf. maybe not.
    server_conf="$OVPN_ORGNICK-server.conf"
    table_body=$(Open_Table_Section)

    #TODO: Can we get this from the server conf?
    openvpn_index="/var/lib/openvpn-server/openssl/index.txt"
    for vpn_name in `grep ^V $openvpn_index | grep CN | grep -v "OpenVPN server on" | sed -e "s/\/emailAddress//g" |  awk -F"=" {'print $5'}`; do

        ## Details of current status
        #tail /var/lib/openvpn-server/openvpn/status.log | grep ltu-kit01 | tail -n1 | awk -F"," {'print $2 " " $1 " " $3 " " $4'} | sed -e 's/:[0-9]\{3,5\}//g'

        connected_user=""
        connected_user=$(grep "^CLIENT_LIST" "$status_log" | grep $vpn_name | sed -e "s/:[0-9]\{3,5\}//g")

        public_ip=""
        public_ip=$(echo $connected_user | cut -f3 -d",")

        vpn_ip=""
        if [ -f "/etc/openvpn/ccd/$vpn_name" ]; then
                vpn_ip=$(grep ifconfig-push /etc/openvpn/ccd/$vpn_name | cut -f2 -d' ')
        fi

        connected_since=""
        row_class=""

        # Write out the main html
        if [ "$vpn_name" == "$this_vpnname" ]; then     # is triggering user
            if [ "$connection_type" == "connect" ]; then
                row_class="$connection_type connected"
                vpn_ip=$this_ip
                connected_since=$(echo $connected_user | cut -f7 -d",")
            else
                row_class="$connection_type"
            fi

        elif grep -q $vpn_name "$status_log" ; then                # non triggering connected user
            row_class="connected"
                vpn_ip=$(echo $connected_user | cut -f4 -d",")
                connected_since=$(echo $connected_user | cut -f7 -d",")

        else                                            # not connected
            echo -n ""
        fi
        table_body+=$(Create_Table_Row)

    done

    table_body+=$(Close_Table_Section)

        generated_details=`echo $generated_details | sed 's/</\\\\\</g; s/>/\\\\\>/g; s/"/\\\\\"/g;'`
        table_body=`echo $table_body | sed 's/</\\\\\</g; s/>/\\\\\>/g; s/"/\\\\\"/g;'`

    #TODO: These should be going from the template to the tmp file
    cp "$template_html" "$tmp_html"
    sed -i -e "s|%%SCRIPTNAME%%|$script_name|g" -e "s|%%GENERATED_DETAILS%%|$generated_details|g" -e "s|%%TABLE_BODY%%|$table_body|g" "$tmp_html"

    if [ "" != "$live_html" ]; then
        cp "$tmp_html" "$live_html"
    fi

    exit 0


}


function Echo_Status() {

    grep CLIENT_LIST "$status_log" | head -n1 | sed -e "s/HEADER,//g" | awk -F "," '{printf "%-20s %-18s %-18s %-25s %14s %12s       Routes\n",$2,$3,$4,$7,$5,$6}'

    for client in $(grep ^CLIENT_LIST "$status_log" | awk -F "," '{print $2}'); do
        row=$(grep ^CLIENT_LIST "$status_log" | sed -e "s/:[0-9]\{3,5\}//g" | grep "$client")
        routes=$(grep ^ROUTING_TABLE "$status_log" | grep "$client" | awk -F  "," '{printf "%s|",$2}')
        echo "$row,${routes::-1}" | awk -F "," '{printf "%-20s %-18s %-18s %-25s %11.0f MB %9.0f MB   %2s\n",$2,$3,$4,$7,$5/1024/1024,$6/1024/1024,$10}'
    done
                
                echo " "
                Bandwidth
}

function Bandwidth() {
    # TODO: This needs fixing to show interface, ip, mac and send/recieve amounts
	echo "Tun0 IP is: `ip -br address |grep tun|awk '{print $3}'`"
	echo "Stats for Tun0:
	`ip -s link show dev tun0`"
    echo "4secs of bandwidth snapshot"
    ifstat -i tun0 1 4
}

if [ -f /var/lib/openvpn-server/ca-store ]
then
    if grep -q ca-store /proc/mounts
    then
        echo "ca-store mounted"
    else
        echo "ca-store not mounted, or your session has expired."
        echo "Use ovs mount-ca-store to mount your ca-store"
        exit 1
    fi

fi
script_name="$0"

. /etc/openvpn-server/config.sh

status_log=`grep "status " /etc/openvpn/$OVPN_ORGNICK-server.conf |cut -f2 -d ' '`
connection_type=""

if grep -q "status-version 2" "/etc/openvpn/$OVPN_ORGNICK-server.conf" ; then
        
        case $1 in
            --help)
                Usage
                ;;
            --html|--connect|--disconnect)
              connection_type=`echo "$1" | sed -e "s/-//g"`
                Create_Html_Status
                ;;
            *)
                Echo_Status
                ;;
        esac

else
	if [ "$CAONLY" == "yes" ]
	then
		echo "Connecting to `cat /etc/openvpn-server/servers.conf` to get status"
			for server in `cat /etc/openvpn-server/servers.conf`
	                do ssh -i "/var/lib/openvpn-server/openssl/ssh-keys/id_rsa" $server cat $status_log
        	        done

	else
        	echo "INFO: Add the line 'status-version 2' to /etc/openvpn/$OVPN_ORGNICK-server.conf for fancy or html output"
	        echo " "
	        cat $status_log
	        echo " "
	        Bandwidth
	fi

fi
