#!/bin/bash

set -x

function pingcheck {
  ping -c 1 -W 1 google.com > /dev/null
  if [[ $? == 0 ]]; then
    echo "All good! Nothing to do."
  else
    echo "No connectivity! Let's fix it."
    fixit
  fi
}

function am_i_connected {
  check=$(nmcli -f NAME,DEVICE c show --active | sift '@Wireless' | wc -l)
  if [[ $check != 0 ]]; then
    echo true
  fi
}

function am_i_connected_to_something {
  check=$(nmcli -f NAME,DEVICE c | sift wlp9s0 | wc -l)
  if [[ $check != 0 ]]; then
    echo true
  fi
}

function bring_it_down {
  UUID=$(nmcli -f DEVICE,UUID c show --active | sift wlp9s0 | awk '{print $2}')
  nmcli c down $UUID
}

function bring_it_up {
  UUID=$(nmcli -f NAME,UUID c | sift '@Wireless' | awk '{print $2}')
  nmcli c up $UUID passwd-file /home/tyler/shellscripts/wirelesslogin/passwd-file
}

function spoofy_doof {
  UUID=$(nmcli -f NAME,UUID,DEVICE c show | sift -e 'ESAconnect' | awk '{print $2}')
  nmcli c modify --temporary $UUID 802-11-wireless.cloned-mac-address 30:85:A9:6B:C6:F8
  sleep 3
  nmcli c up $UUID
  curl https://esaconnect.extendedstayamerica.com/?param=cGlkPTk4MjgmZGV2aWNlSVA9MTcyLjE2LjAuOTEmZGV2aWNlTUFDPUIwMzU5RjJCQzVBMCZwcm9wZXJ0eVR5cGU9Tm9ybWFs
  curl https://esaconnect.extendedstayamerica.com//wificonfirmlanding?param=cGlkPTk4MjgmZGV2aWNlSVA9MTcyLjE2LjAuOTEmZGV2aWNlTUFDPUIwMzU5RjJCQzVBMCZwcm9wZXJ0eVR5cGU9Tm9ybWFs
  # curl https://esaconnect.extendedstayamerica.com//wificonfirmlanding?param=cGlkPTk4MjgmZGV2aWNlSVA9MTcyLjE2LjAuMjEmZGV2aWNlTUFDPTE0RERBOTZGQ0JFNCZwcm9wZXJ0eVR5cGU9Q2hlZXRhaA%3D%3D
  # curl https://esaconnect.extendedstayamerica.com/?param=cGlkPTk4MjgmZGV2aWNlSVA9MTcyLjE2LjAuMjEmZGV2aWNlTUFDPTE0RERBOTZGQ0JFNCZwcm9wZXJ0eVR5cGU9Q2hlZXRhaA%3D%3D
  bring_it_down
}

function reboot_router {
  eval "{ sleep 1; echo o0beaner; sleep 1; echo d0ubl3h1gh\!\!; sleep 1; echo 'reboot'; sleep 2; }" | telnet 172.16.0.224
}

function fixit {
  if [[ $(am_i_connected) != true ]]; then
    if [[ $(am_i_connected_to_something) == true ]]; then
      bring_it_down
      sleep 2
    fi
    bring_it_up
  fi

  reboot_router
  bring_it_down
  spoofy_doof
  bring_it_up

  i=0
  until [[ $(am_i_connected) == true || $i == 20 ]]; do
    sleep 5
    bring_it_up
    ((i++))
  done
}

if [[ $(am_i_connected) == true ]]; then
  pingcheck
else
  bring_it_up
  pingcheck
fi
