#!/bin/sh
port=$1
## build tunnel
cloud_ip=34.210.248.103
external_ssh=$port
internal_ssh=`dc -e "$external_ssh 16000 + p"`
external_http=`dc -e "$internal_ssh 16000 + p"`
internal_http=`dc -e "$external_http 16000 + p"`
echo $external_ssh $internal_ssh $external_http $internal_http
#pkill -f "ssh -o StrictHostKeyChecking=no -R"
#pkill -f "ssh -o StrictHostKeyChecking=no -f -i"
t=`curl --connect-timeout 30 --max-time 10 -s https://mysiteconnect.com:$external_http/common/tct.html`
echo $t
if test ! -z $t
then
        if test $t = "success"
        then
                exit 0
        fi
fi
curl --connect-timeout 30 --max-time 10 -s https://phason.ca > /tmp/curlxxx
curl_return=$?
echo "network check = " $curl_return
if test $curl_return -ne 0
then
sudo service networking restart
d=`date`
echo $d " networking restart by cloud"
sleep 5
fi

pkill -f "ssh -o StrictHostKeyChecking=no"
ssh -o StrictHostKeyChecking=no -o ConnectTimeout=120 -p 1498 -i cloud_id phason@$cloud_ip sudo /root/get_ssl_cert > /tmp/apache.pem
ssh -o StrictHostKeyChecking=no -o ConnectTimeout=120 -p 1498 -i cloud_id phason@$cloud_ip sudo /root/get_ssl_key > /tmp/apache.key
if test -s /tmp/apache.pem -a -s /tmp/apache.key
then
        if test -e /home/pi/SSD
        then
        sudo cp /tmp/apache.pem /etc/ssl/localcerts/apache.pem
        sudo cp /tmp/apache.key /etc/ssl/localcerts/apache.key
        else
        cp /tmp/apache.key /tmp/config/apache.key
        cp /tmp/apache.pem /tmp/config/apache.pem
        fi
        sudo /etc/init.d/apache2 restart
ssh -o StrictHostKeyChecking=no -o ConnectTimeout=120 -p 1498 -o ServerAliveInterval=30 -o ServerAliveCountMax=5 -R $internal_ssh:localhost:22 -R $external_http:localhost:443 -N -f -i cloud_id phason@34.210.248.103
t=`curl --connect-timeout 30 -s https://mysiteconnect.com:$external_http/common/tct.html`
if test -z $t
then
        t="failed"
fi
curl --connect-timeout 30 --max-time 10 -s http://$cloud_ip/cgi-bin/status.cgi?CON,`date +%D_%T`,`hostname`,`cat /tmp/os/cloud_port`,$t
fi
