#!/usr/bin/env python3
# ***************************************************************************
#  IIIIII NNN  NNN  Copyright (C) 2022 Innovative Networks, Inc.
#    II    NNN  N   All Rights Reserved. Any redistribution or reproduction
#    II    N NN N   of part or all of the content of this program in any form
#    II    N  NNN   without expressed written consent of the copyright holder
#  IIIIII NNN  NNN  is strictly prohibited.  Please contact admins@in-kc.com
#   Be Innovative.  for additional information.
# ***************************************************************************
#  check_http.py
#  Author - Ian Perry <iperry@indigex.com>
#
#  Purpose:  Validates that a website is online
#
#  Version History:
#       2023.06.06 - Initial creation
# ***************************************************************************

try:
    from inmon_utils import *
except:
    import sys

    print("Unable to import inmon utils")
    sys.exit(3)

import requests
import argparse
import urllib3
from urllib.parse import urlparse
import http
http.client._MAXHEADERS = 1000 # Required for certain sites like outlook.

parser = argparse.ArgumentParser(description="Verifies a website is online.")
parser.add_argument("-I", dest="ip_address", help="IP Address or FQDN", required=True)
parser.add_argument("-a", dest="allow_unauthorized", help="Returns OK on 401")
parser.add_argument(
    "-d", dest="debug", help="Enables debugging output", action="store_true"
)
parser.add_argument(
    "-p", "--port", dest="port", help="Specify non-default port", default=80, type=int
)
parser.add_argument(
    "-s", "--enable-https", dest="https", help="Enable HTTPS", action="store_true"
)
args = parser.parse_args()

if args.allow_unauthorized == "true" or args.allow_unauthorized == True:
    allow_unauthorized = True
else:
    allow_unauthorized = False

urllib3.disable_warnings()

# Build the URL and then break it apart.
url_str = f"{'https' if args.https else 'http'}://{args.ip_address}"
url = urlparse(url_str)

response = requests.get(f"{url.scheme}://{url.netloc}:{args.port}{url.path}", verify=False, timeout=30)

secure = "S" if response.url.startswith("https://") else ""
if response.raw.version == 10:
    http_version = "1.0"
elif response.raw.version == 11:
    http_version = "1.1"
else:
    print(f"Unknown HTTP Version Response: {response.raw.version}")
    sys.exit(3)

if response.status_code == 200 or (response.status_code == 401 and allow_unauthorized):
    begin = "[OK]"
    return_status = 0
else:
    begin = "[CRIT]"
    return_status = 2

length = len(response.text)
time = response.elapsed.total_seconds()

print(
    f"{begin} - HTTP{secure}/{http_version} {response.status_code} {response.reason} - {length} bytes in {time} second response time | time={time}s size={length}B"
)
sys.exit(return_status)
