#!/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

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
}

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

# 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

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
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