#!/usr/bin/env bash

DEF_TUNSERVER_NAME="labtun5.dit.upm.es"  # Tunnel server to connect to
DEF_REPSERVER_NAME="idefix.dit.upm.es"    # Server to retrieve the tunnel config from
USAGE="
Usage: 

  install-tun <scenario_letter> [<tun-server> <repository-server>]

  Downloads a tinc tunnel client configuration and starts it. 

  Parameters:
    - <scenario_letter>: letter identifier of the scenario requested (i.e., A)
    - [<tun-server>]: indicates the domain name or IP address of the tunnel 
      server (defaults to $DEF_TUNSERVER_NAME if not specified)
    - [<repository-server>]: indicates the domain name or IP address of the 
      repository where the client configs are stored (defaults to $DEF_REPSERVER_NAME if not specified).
      If <repository-server> is specified, <tun-server> must be specified also.

  Examples:
    install-tun A
    install-tun A $DEF_TUNSERVER_NAME
    install-tun A $DEF_TUNSERVER_NAME $DEF_REPSERVER_NAME
"

if [ "$#" -lt 1 ]; then 
    echo ""
    echo "ERROR: incorrect number of parameters"
    echo "$USAGE"
    exit 1
fi

POD=$1

if [[ $POD != [A-Z] ]] ; then
    echo ""
    echo "ERROR: Unknown scenario id -> $POD"
    echo "$USAGE"
    exit 1
fi

# Test an IP address for validity:
# Usage:
#      if valid_ip IP_ADDRESS; then echo good; else echo bad; fi
# Source: https://www.linuxjournal.com/content/validating-ip-address-bash-script
function valid_ip()
{
    local  ip=$1
    local  stat=1
    if [[ $ip =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then
        OIFS=$IFS
        IFS='.'
        ip=($ip)
        IFS=$OIFS
        [[ ${ip[0]} -le 255 && ${ip[1]} -le 255 \
            && ${ip[2]} -le 255 && ${ip[3]} -le 255 ]]
        stat=$?
    fi
    return $stat
}

# Check lab server address/name
if [ "$2" ]; then
    TUNSERVER=$2
else
    TUNSERVER=$DEF_TUNSERVER_NAME
fi
if ! valid_ip $TUNSERVER; then
    echo "--"
    echo -n "-- lab-server addr ($TUNSERVER) is NOT a valid IPv4 address. Resolving..."
    # It should be a domain name
    TUNSERVER_IP=$( host $TUNSERVER | awk '/has address/ { print $4 }' )
    if ! valid_ip $TUNSERVER_IP; then
        echo "NOTOK"
        echo "-- ERROR: cannot get the IP address asociated to '$TUNSERVER'. Installation aborted."
        echo "--"
	    exit 1
    else
        echo "OK ($TUNSERVER_IP)"
    fi
    SHORT_TUNSERVER_NAME=$( echo "$TUNSERVER" | cut -d "." -f 1 )
    TUNSERVER_NAME=$TUNSERVER
else
    # The parameter provided is an IP address
    TUNSERVER_NAME=$TUNSERVER 
    TUNSERVER_IP=$TUNSERVER 
fi

# Check repository server address/name
if [ "$3" ]; then
    REPSERVER=$3
else
    REPSERVER=$DEF_REPSERVER_NAME
fi
if ! valid_ip $REPSERVER; then
    echo "--"
    echo -n "-- repository-server addr ($REPSERVER) is NOT a valid IPv4 address. Resolving..."
    # It should be a domain name
    REPSERVER_IP=$( host $REPSERVER | awk '/has address/ { print $4 }' )
    if ! valid_ip $REPSERVER_IP; then
        echo "NOTOK"
        echo "-- ERROR: cannot get the IP address asociated to '$REPSERVER'. Installation aborted."
        echo "--"
	    exit 1
    else
        echo "OK ($REPSERVER_IP)"
    fi
    REPSERVER_NAME=$REPSERVER
else
    # The parameter provided is an IP address
    REPSERVER_NAME=$REPSERVER 
    REPSERVER_IP=$REPSERVER 
fi


echo "--"
echo "-- install-tun"
echo "--   POD=$POD, LAB_SERVER=$TUNSERVER_NAME($TUNSERVER_IP), REPO_SERVER=$REPSERVER_NAME($REPSERVER_IP)"
echo "--"
echo "-- Downloading scenario $POD..."
PODNUM=$(( $( printf '%d' "'$POD" ) - 64 ))
PODNUMPADED=$( printf "%03d\n" $PODNUM )
TUNCFGFNAME="tinc-sede${PODNUMPADED}.tgz"

echo $PODNUM
echo $TUNCFGFNAME

rm -f $TUNCFGFNAME
TMPDIR=$( mktemp -d -t tinc-XXXX ) 
cd $TMPDIR
echo "-- Downloading scenario $TUNCFGFNAME..."
wget $REPSERVER_NAME/download/rdsv/tinc2/${TUNCFGFNAME} -O ${TUNCFGFNAME} -c
if [ $? -ne 0 ]; then
    echo "--"
    echo "-- ERROR: cannot download scenario $TUNCFGFNAME"
    exit 1
fi

# Unpack scenario and enter the directory
echo "-- Unpacking scenario $TUNCFGFNAME..."
sudo tar xfvz ${TUNCFGFNAME}
cd sede???

AUX=$( cat vnxtun${POD}/hosts/vnxtunserver | grep Subnet )
AUX=(${AUX//=/ })
LAB_SERVER_TUN=${AUX[1]::-3}

ETCHOSTS=/etc/hosts

#
# Add tunserver entry to /etc/hosts
#
# Delete old entry if it exists
sudo sed -i -e '/.*tunserver/d' $ETCHOSTS
echo "-- Adding '$TUNSERVER_IP  vnxtunserver' entry to $ETCHOSTS"
sudo sh -c "echo \"$TUNSERVER_IP vnxtunserver\" >> $ETCHOSTS"

echo "-- Copying tinc configuration to /etc/tinc..."
# Configure and start tinc VPN
sudo killall tincd 2> /dev/null
sleep 2
#sudo /etc/init.d/tinc stop
sudo mkdir -p /etc/tinc    # Just in case it has been deleted
sudo rm -rf /etc/tinc/*
sudo cp -a * /etc/tinc

# Enable and start tinc service 
sleep 2
sudo systemctl enable tinc
sudo systemctl enable tinc@vnxtun${POD}.service 
sudo systemctl start tinc@vnxtun${POD}.service

echo "-- Checking connectivity to server side of the tunnel..."
if ping -c 3 $LAB_SERVER_TUN; then
    echo "-- Connection to server OK."
else
    echo "-- WARNING: cannot ping to tunnel server side ($LAB_SERVER_TUN)."
fi

# Save lab server ssh fingerprint
sudo bash -c "ssh-keyscan -H $LAB_SERVER_TUN >> /root/.ssh/known_hosts"

[ ! -z $TMPDIR ] && sudo rm -rf $TMPDIR

echo "-- "
echo "-- Tunnel server IP addr=$LAB_SERVER_TUN"
echo "-- Tunnel local  IP addr="$(ip -f inet -o addr show vnxtun$POD | cut -d\  -f 7 | cut -d/ -f 1)
echo "-- "
echo "-- ...hecho"

