#!/usr/bin/env bash

# Microsoft Azure Linux Agent
#
# Copyright 2018 Microsoft Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Helper script which tries to access Wireserver on system reboot. Also prints out iptable rules if non-root and still
# able to access Wireserver

if [[ $# -ne 1 ]]; then
    echo "Usage: agent_persist_firewall-access_wireserver <test-user>"
    exit 1
fi
TEST_USER=$1
USER=$(whoami)
echo "$(date --utc +%FT%T.%3NZ): Running as user: $USER"

function check_online
{
    ping 8.8.8.8 -c 1 -i .2 -t 30 > /dev/null 2>&1 && echo 0 || echo 1
}

function ping_localhost
{
    ping 127.0.0.1 -c 1 -i .2 -t 30 > /dev/null 2>&1 && echo 0 || echo 1
}

function socket_connection
{
    output=$(python3 /home/"$TEST_USER"/bin/agent_persist_firewall-check_connectivity.py 2>&1)
    echo $output
}

# Check more, sleep less
MAX_CHECKS=10
# Initial starting value for checks
CHECKS=0
IS_ONLINE=$(check_online)

echo "Checking network connectivity..."
echo "Running ping to 8.8.8.8 option"
# Loop while we're not online.
while [ "$IS_ONLINE" -eq 1 ]; do

    CHECKS=$((CHECKS + 1))
    if [ $CHECKS -gt $MAX_CHECKS ]; then
        break
    fi

    echo "$(date --utc +%FT%T.%3NZ): Network still not accessible"
    # We're offline. Sleep for a bit, then check again
    sleep 1;
    IS_ONLINE=$(check_online)

done

# logging other options output to compare and evaluate which option is more stable when ping to 8.8.8.8 failed
if [ "$IS_ONLINE" -eq 1 ]; then
    echo "Checking other options to see if network is accessible"
    echo "Running ping to localhost option"
    PING_LOCAL=$(ping_localhost)
    if [ "$PING_LOCAL" -eq 1 ]; then
        echo "Ping to localhost failed"
    else
        echo "Ping to localhost succeeded"
    fi
    echo "Running socket connection to wireserver:53 option"
    socket_connection
fi
if [ "$IS_ONLINE" -eq 1 ]; then
    # We will never be able to get online. Kill script.
    echo "Unable to connect to network, exiting now"
    echo "ExitCode: 1"
    exit 1
fi

echo "Finally online, Time: $(date --utc +%FT%T.%3NZ)"
echo "Trying to contact Wireserver as $USER to see if accessible"

echo ""
echo "IPTables before accessing Wireserver"
sudo iptables -t security -L -nxv -w
echo ""

WIRE_IP=$(cat /var/lib/waagent/WireServerEndpoint 2>/dev/null || echo '168.63.129.16' | tr -d '[:space:]')
if command -v wget >/dev/null 2>&1; then
    wget --tries=3 "http://$WIRE_IP/?comp=versions" --timeout=5 -O "/tmp/wire-versions-$USER.xml"
else
    curl --retry 3 --retry-delay 5 --connect-timeout 5 "http://$WIRE_IP/?comp=versions" -o "/tmp/wire-versions-$USER.xml"
fi
WIRE_EC=$?
echo "ExitCode: $WIRE_EC"

if [[ "$USER" != "root" && "$WIRE_EC" == 0  ]]; then
  echo "Wireserver should not be accessible for non-root user ($USER)"
fi

if [[ "$USER" != "root" ]]; then
echo ""
echo "checking tcp traffic to wireserver port 53 for non-root user ($USER)"
echo -n 2>/dev/null < /dev/tcp/$WIRE_IP/53 && echo 0 || echo 1  # Establish network connection for port 53
TCP_EC=$?
echo "TCP 53 Connection ExitCode: $TCP_EC"
fi