#!/usr/bin/env python2.7
"""
Retrieves configuration from the Zero Touch Deployment Portal
Usage:  ztdclient [ Arguments | Flags ]
Arguments:
  -s, --serial          serial number to report defaults to the serial number of the appliance
  -K, --secret          shared secret to report defaults to that burnt onto the appliance
  -m, --mfg_version     firmware version to report defaults to the version of the firmware on this appliance
  -o, --output          folder to write any downloaded configuration to defaults to /opt/phion/update
  -k, --privatekey      RSA key to sign messages with defaults to the box RSA key
  -H, --host            Address of the Zero Touch Portal to connect to defaults to ztd.barracudanetworks.com
  -P, --port            HTTPS Port on the Portal defaults to 443
  -p, --http_port       HTTP Port on the Portal defaults to 80

Flags:
  -h, --help            show this help
  -d, --dryrun          dry run only, don't install the config
  -D, --debug           printing useful logs relating to requests & responses for nonces
  -i, --insecure        ignore SSL certificate errors
  -r, --report          start up in error reporting mode
  -c, --check           start up in check for connection mode
"""

from urllib2 import Request, urlopen, URLError, HTTPError
import getopt
import sys
import tempfile
import os
import shutil
import json
import ssl
import datetime
import subprocess
import hashlib
import hmac
import base64
import re
import socket
import time
import threading

try:
    import phionlibs
except ImportError:
    pass

talked_to_cc = False
script_version = "1.0.6"
nonce = None
privatekey = None
shared_secret = None
user_agent = None

try:
    from phionlibs import CPLog
    from phionlibs import CPLogger

    plog = CPLog('/var/phion/logs/')
    plogger = CPLogger('box_Config_daemon', 0, plog, 'bnzt')
except ImportError:
    # if phionlibs is not usable, create our own basic plogger
    class Plogger:
        def __init__(self, logdirectory, logfile):
            self.f = open(logdirectory + '/' + logfile, 'a+')
            self.utcoffset = "+00:00".ljust(7)

        def formatted_date(self):
            return str(datetime.datetime.strftime(datetime.datetime.now(), "%Y %m %d %H:%M:%S "))

        def ILOG(self, message):
            self.f.write(self.formatted_date() + "Info".ljust(9) + self.utcoffset + message + "\n")
            self.f.flush()

        def WLOG(self, message):
            self.f.write(self.formatted_date() + "Warning".ljust(9) + self.utcoffset + message + "\n")
            self.f.flush()

        def NLOG(self, message):
            self.f.write(self.formatted_date() + "Notice".ljust(9) + self.utcoffset + message + "\n")
            self.f.flush()

        def ELOG(self, message):
            self.f.write(self.formatted_date() + "Error".ljust(9) + self.utcoffset + message + "\n")
            self.f.flush()

        def FLOG(self, message):
            self.f.write(self.formatted_date() + "Fatal".ljust(9) + self.utcoffset + message + "\n")
            self.f.flush()


    plogger = Plogger('/var/log', 'ztdclient.log')


class Firewall:
    def __init__(self):
        pass

    def check_cc_connection(self, duration):
        plogger.ILOG("Checking for CC Traffic, max check duration = " + str(duration))
        time.sleep(60)  # wait for quiescence
        self.write_cc_file()
        thread = threading.Thread(target=self.capture_cc_traffic, args=())
        thread.start()
        thread.join(duration)
        self.clear_cc_file()
        plogger.ILOG("Checking completed, got traffic = " + str(talked_to_cc))
        return talked_to_cc

    def has_stop_flag(self):
        return os.path.isfile(self.flagFileDirectory + "/ztdstopflag")

    def clear_stop_flag(self):
        if self.has_stop_flag():
            os.unlink(self.flagFileDirectory + "/ztdstopflag")

    def write_stop_flag(self):
        stop_file = open(self.flagFileDirectory + "/ztdstopflag", "w")
        stop_file.write("")
        stop_file.close()

    def has_revert_flag(self):
        return os.path.isfile(self.flagFileDirectory + "/ztdcheck")

    def clear_revert_flag(self):
        if self.has_revert_flag():
            os.unlink(self.flagFileDirectory + "/ztdcheck")

    def write_revert_flag(self, revert_timer):
        revert_flag = open(self.flagFileDirectory + "/ztdcheck", "w")
        revert_flag.write(str(revert_timer))
        revert_flag.close()

    def process_revert_flag(self):
        if not os.path.isfile(self.flagFileDirectory + "/ztdcheck"):
            plogger.ELOG(
                "No revert flag at " + self.flagFileDirectory + "/ztdcheck - not running post configuration checks")
            return 0
        revert_flag = open(self.flagFileDirectory + "/ztdcheck", "r")
        value = revert_flag.read()
        revert_flag.close()
        self.clear_revert_flag()

        timeout = 0
        try:
            timeout = int(value)
        except ValueError:
            plogger.ELOG("Non numeric timeout value in revert check - not running post configuration checks")

        return timeout

    def has_stats(self):
        return os.path.isfile(self.flagFileDirectory + "/ztdstats")

    def write_stats(self, stats):
        stats_file = open(self.flagFileDirectory + "/ztdstats", "w")
        stats_file.write(stats)
        stats_file.close()

    def process_stats(self):
        stats_file = open(self.flagFileDirectory + "/ztdstats", "r")
        my_stats = stats_file.read()
        stats_file.close()
        return my_stats

    def clear_stats(self):
        os.unlink(self.flagFileDirectory + "/ztdstats")

    def get_ip_address(self, host, port):
        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            s.connect((host, int(port)))
            return s.getsockname()[0]
        except Exception, o:
            plogger.ELOG("Unable to read the local IP Address, returning 127.0.0.1")
            return "127.0.0.1"


class FSeries(Firewall):
    def __init__(self):
        Firewall.__init__(self)
        self.flagFileDirectory = '/tmp'
        self.configOutput = '/opt/phion/update/box.ppar'

    def get_model(self):
        conf = phionlibs.CStdConfig()
        conf.LoadPath('/opt/phion/config/active', 'box.conf')
        return conf.Get('/', 'boxmodel')

    def reboot_box(self):
        subprocess.Popen("reboot").communicate()

    def capture_cc_traffic(self):
        global talked_to_cc
        now = int(time.time())

        while True:
            time.sleep(60)
            with open("/phion0/run/controld/cc_access.stamp") as f:
                data = f.readlines()
                if data:
                    lastline = data[-1]
                    stamp = int(lastline)
                    if stamp > now:
                        talked_to_cc = True
                        break

    def has_backup(self):
        return os.path.isfile(self.flagFileDirectory + "/revert.par")

    def remove_backup(self):
        os.unlink(self.flagFileDirectory + "/revert.par")

    def make_backup(self):
        try:
            subprocess.Popen(
                "cd /opt/phion/config/configroot;/opt/phion/bin/phionar cd " + self.flagFileDirectory + "/revert.par *",
                stdout=subprocess.PIPE, shell=True)
            plogger.ILOG("backup of current configuration save to " + self.flagFileDirectory + "/revert.par")
        except Exception, o:
            plogger.ELOG("Unable to create revert.par backup file")

    def reapply_backup(self):
        os.rename(self.flagFileDirectory + "/revert.par", "/opt/phion/update/box.par")
        self.reboot_box()

    def is_enabled(self):
        conf = phionlibs.CStdConfig()
        conf.LoadPath('/opt/phion/config/active', 'box.conf')
        s = conf.Get('/', 'dozerotouch')
        m = conf.Get('/', 'mainadmin')
        enabled = (s == 'y') and (m == 'n')
        plogger.ILOG("Zero Touch is " + str(enabled))
        return enabled

    def collect_stats(self):
        try:
            p1 = subprocess.Popen(["/opt/phion/bin/version.py", "-t", "ALL", "-F", "ini"], stdout=subprocess.PIPE)
            my_stats, stderr = p1.communicate()
            if stderr:
                plogger.ELOG("Unable to collect box stats")
                return "Stats unavailable"
            else:
                plog1 = subprocess.Popen(["awk", "$7 ~ /bnzt/", "/var/phion/logs/box_Config_daemon.log"], stdout=subprocess.PIPE)
                plog2 = subprocess.Popen(["tail", "-n 100"], stdin=plog1.stdout, stdout=subprocess.PIPE)
                plog1.stdout.close()
                logs, stderr = plog2.communicate()
                if stderr:
                    plogger.ELOG("Unable to collect logs")
                else:
                    my_stats += "[LOG]\n" + logs
                return my_stats
        except Exception, o:
            plogger.ELOG("Unable to collect box stats")
            return "Stats unavailable"

    def write_cc_file(self):
        cc_file = open("/phion0/run/controld/cc_access.stamp", "w")
        cc_file.write("")
        cc_file.close()

    def has_cc_file(self):
        return os.path.isfile("/phion0/run/controld/cc_access.stamp")

    def clear_cc_file(self):
        if self.has_cc_file():
            os.unlink("/phion0/run/controld/cc_access.stamp")

    def read_version(self):
        version = None
        try:
            f = open("/etc/phion-release", 'r')
            data = f.read()
            f.close()
            g = re.search(r"(\d+)\.(\d+)\.(\d+)-(\d+)", data)
            if g:
                gs = g.groups()
                version = "%s-%s" % (".".join(g.groups()[:-1]), gs[-1])
        except Exception, e:
            plogger.ELOG("Unable to read /etc/phion-release")

        return version

    def read_serial(self):
        try:
            p1 = subprocess.Popen(["/opt/phion/bin/hwtool", "-s"], stdout=subprocess.PIPE)
            key_data, stderr = p1.communicate()
            if stderr:
                plogger.ELOG("Unable to read box serial")
                return None
            else:
                lines = iter(key_data.splitlines())
                my_serial = lines.next()

                return my_serial
        except Exception, o:
            plogger.ELOG("Unable to read box serial")
            return None

    def read_secret(self):
        try:
            p1 = subprocess.Popen(["/opt/phion/bin/barracuda-key", "-s", "-d", "/dev/sda"], stdout=subprocess.PIPE)
            key_data, stderr = p1.communicate()
            if stderr:
                plogger.ELOG("Unable to read shared secret")
                return None
            else:
                lines = iter(key_data.splitlines())
                my_key = lines.next()

                return my_key
        except Exception, o:
            plogger.ELOG("Unable to read shared secret")
            return None

    def read_barracuda_key(self):
        try:
            p1 = subprocess.Popen(["/opt/phion/bin/barracuda-key", "-z", "-d", "/dev/sda"], stdout=subprocess.PIPE)
            key_data, stderr = p1.communicate()
            if stderr:
                plogger.ELOG("Unable to read box keys")
                return None
            else:
                lines = iter(key_data.splitlines())
                return list(lines)
        except Exception, o:
            plogger.ELOG("Unable to read box keys")
            return None

    def install_config(self, tmpfile, output, dry_run):
        plogger.ILOG("copying " + tmpfile.name + " to " + output)
        if not dry_run:
            if os.path.isfile(output):
                os.unlink(output)
            shutil.copy(tmpfile.name, output)
            thisFirewall.write_stop_flag()

    def webui_change_pending(self):
        pending_change = (os.path.isfile('/home/bfw/code/firmware/webui-install-init.pending')) \
                         or (os.path.isfile('/home/bfw/code/firmware/webui-update-init.pending'))
        return pending_change

    def webui_enabled(self):
        conf = phionlibs.CStdConfig()
        conf.LoadPath('/opt/phion/config/active', 'box.conf')
        w = conf.Get('/', 'ismanagedbywebui')
        enabled = (w == 'y')
        plogger.ILOG("Web UI is " + str(enabled))
        return enabled

    def finished_sound(self, success):
        if success:
            soundId = "1"
        else:
            soundId = "2"
        subprocess.Popen(["/opt/phion/bin/hwtool", "-a", soundId])

class SSeries(Firewall):
    def __init__(self):
        Firewall.__init__(self)
        self.flagFileDirectory = '/var/phion/run'
        self.configOutput = '/mass-storage/sca.conf'

    def get_model(self):
        return self.getScaConfValue("SCACONFMODEL")

    def reboot_box(self):
        remount_mass_storage = subprocess.Popen(["/bin/mount", "-o", "remount,ro", "/mass-storage"])
        remount_mass_storage.wait()
        subprocess.Popen(["/opt/phion/bin/scactl", "--reboot"]).communicate()

    def capture_cc_traffic(self):
        global talked_to_cc
        p1 = subprocess.Popen(
            ["/usr/sbin/tcpdump", "-i", "tap3", "-n", "-Q", "in", "-l", "udp", "and", "dst", "port", "889"],
            stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        while not talked_to_cc:
            line = p1.stdout.readline()
            if "UDP" in line:
                plogger.ILOG(line)
                talked_to_cc = True
                break

    def getScaConfValue(self, key, configFile="/opt/phion/config/active/sca.conf"):
        try:
            f = open(configFile, mode="r")
            for line in f:
                if line[0:len(key)] == key:
                    key, value = line.split("=")
                    f.close()
                    return value.strip()
            return None
        except IOError:
            raise IOError

    def getScaCtlValue(self, key, subcommand):
        try:
            p1 = subprocess.Popen(["/opt/phion/bin/scactl", "--" + subcommand], stdout=subprocess.PIPE)
            scactl_output, stderr = p1.communicate()
            for line in iter(scactl_output.splitlines()):
                if line[0:len(key)] == key:
                    key, value = line.split("=")
                    return value.strip()
            return None
        except OSError:
            raise OSError

    def getScaCtlOutput(self, subcommand):
        try:
            p1 = subprocess.Popen(["/opt/phion/bin/scactl", "--" + subcommand], stdout=subprocess.PIPE)
            scactl_output, stderr = p1.communicate()
            return str(scactl_output).strip()
        except OSError:
            raise OSError

    def has_backup(self):
        return os.path.isfile("/opt/phion/config/sca/fallback/default.conf")

    def remove_backup(self):
        pass

    def make_backup(self):
        pass

    def reapply_backup(self):
        breakLock = subprocess.Popen(["/opt/phion/bin/scactl", "--breakconfiglock"], stdout=subprocess.PIPE)
        breakLock.wait()
        lockConfig = subprocess.Popen(["/opt/phion/bin/scactl", "--lockconfig", "ztdrevert"], stdout=subprocess.PIPE)
        lockConfig.wait()
        if lockConfig.returncode != 0:
            plogger.FLOG("FSC configuration could not be locked")
            sys.exit(0)
        restoreDefaultConfig = subprocess.Popen(["/opt/phion/bin/scactl", "--restoredefaultconfig"],
                                                stdout=subprocess.PIPE)
        restoreDefaultConfig.wait()
        activateConfig = subprocess.Popen(["/opt/phion/bin/scactl", "--activateconfigfull"], stdout=subprocess.PIPE)
        activateConfig.wait()
        unlockConfig = subprocess.Popen(["/opt/phion/bin/scactl", "--unlockconfig", "ztdrevert"],
                                        stdout=subprocess.PIPE)
        unlockConfig.wait()
        self.reboot_box()

    def is_enabled(self):
        # s = getScConf("DOZEROTOUCH")
        # m = getScConf("MAINADMIN")
        # enabled = (s == 'y') and (m == 'n')
        # plogger.ILOG("Zero Touch is " + str(enabled))
        # return enabled
        return True

    def collect_stats(self):
        try:
            status = self.getScaCtlOutput("getdevicestatus")
            if not status:
                plogger.ELOG("Unable to collect box stats")
                return "Stats unavailable"
            else:
                my_stats = "[DEVICE STATUS]\n" + status
                plog = subprocess.Popen(["tail", "-n 100", "/var/log/ztdclient.log"], stdout=subprocess.PIPE)
                logs, stderr = plog.communicate()
                if stderr:
                    plogger.ELOG("Unable to collect logs")
                else:
                    my_stats += "\n[LOG]\n" + logs
                return my_stats
        except Exception, o:
            plogger.ELOG("Unable to collect box stats")
            return "Stats unavailable"

    def write_cc_file(self):
        pass

    def has_cc_file(self):
        return False

    def clear_cc_file(self):
        pass

    def read_version(self):
        version = None
        try:
            scactl_output = self.getScaCtlValue("FIRMWAREVERSION", "getdevicestatus")
            g = re.search(r"(\d+)\.(\d+)\.(\d+)", scactl_output)
            if g:
                gs = g.groups()
                version = "%s" % (".".join(g.groups()))
        except Exception, o:
            plogger.ELOG("Unable to read firmware version")

        return version

    def read_serial(self):
        try:
            my_serial = self.getScaCtlOutput("readserial")
            return my_serial
        except Exception, o:
            plogger.ELOG("Unable to read box serial")
            return None

    def read_secret(self):
        try:
            shared_secret = self.getScaCtlOutput("readsecret")
            return shared_secret
        except Exception:
            plogger.ELOG("Unable to read shared secret")
            return None

    def read_barracuda_key(self):
        try:
            key_data = self.getScaCtlOutput("readbarracudakey")
            lines = iter(key_data.splitlines())
            return list(lines)
        except Exception:
            plogger.ELOG("Unable to read box key")
            return None

    def install_config(self, tmpfile, output, dry_run):
        plogger.ILOG("copying " + tmpfile.name + " to " + output)
        if not dry_run:
            remount_mass_storage = subprocess.Popen(["/bin/mount", "-o", "remount,rw", "/mass-storage"],
                                                    stdout=subprocess.PIPE)
            remount_mass_storage.wait()
            if os.path.isfile("/opt/phion/config/sca/last_kscfg"):
                os.unlink("/opt/phion/config/sca/last_kscfg")
            if os.path.isfile(output):
                os.unlink(output)
            shutil.copy(tmpfile.name, output)
            thisFirewall.write_stop_flag()

    def webui_change_pending(self):
        return False

    def webui_enabled(self):
        return False

    def finished_sound(self, success):
        pass

def main():
    plogger.ILOG("Starting Barracuda Zero Touch Deployment client")
    global thisFirewall
    global privatekey
    global nonce
    global shared_secret
    global user_agent
    global insecure_ssl_context
    insecure_ssl_context = ssl.create_default_context()
    insecure_ssl_context.check_hostname = False
    insecure_ssl_context.verify_mode = ssl.CERT_NONE

    try:
        conf = phionlibs.CStdConfig()
        conf.LoadPath('/opt/phion/config/active', 'box.conf')
        conf.Get('/', 'boxmodel')
        thisFirewall = FSeries()
    except NameError:
        try:
            SSeries.getScaConfValue(SSeries(), "SCACONFMODEL")
            thisFirewall = SSeries()
        except IOError:
            plogger.FLOG("No NG Firewall was found")
            sys.exit(0)

    try:
        opts, args = getopt.getopt(sys.argv[1:], "K:rcs:ho:dDH:P:p:ik:m:",
                                   ["secret=", "report", "check", "serial=", "help", "output=", "dryrun", "debug",
                                    "host=", "port=", "http_port=", "insecure", "privatekey=", "mfg_version="])
    except getopt.GetoptError, err:
        # print help information and exit:
        plogger.ELOG(str(err))  # will print something like "option -a not recognized"
        sys.exit(0)

    output = None
    mfg_version = None
    my_serial = None
    dry_run = False
    debug = False
    insecure = False
    host = "ztd.barracudanetworks.com"
    port = "443"
    http_port = "80"
    privatekey = None
    key_file = None
    do_check = False
    do_report = False

    for o, a in opts:
        if o in ("-m", "--mfg_version"):
            mfg_version = a
        elif o in ("-r", "--report"):
            do_report = True
        elif o in ("-c", "--check"):
            do_check = True
        elif o in ("-d", "--dryrun"):
            dry_run = True
        elif o in ("-D", "--debug"):
            debug = True
        elif o in ("-i", "--insecure"):
            insecure = True
        elif o in ("-s", "--serial"):
            my_serial = a
        elif o in ("-K", "--secret"):
            shared_secret = a
        elif o in ("-h", "--help"):
            usage()
            sys.exit()
        elif o in ("-o", "--output"):
            output = a
        elif o in ("-k", "--privatekey"):
            key_file = a
        elif o in ("-H", "--host"):
            host = a
        elif o in ("-P", "--port"):
            port = a
        elif o in ("-p", "--http_port"):
            http_port = a
        else:
            assert False, "unhandled option"

    if not thisFirewall.is_enabled() and not (do_check or do_report):
        plogger.ELOG("Zero Touch is disabled in active/box.conf")
        sys.exit(0)

    if not shared_secret:
        shared_secret = thisFirewall.read_secret()
        if not shared_secret:
            plogger.ELOG("Unable to retrieve shared secret")
            sys.exit(0)

    if not my_serial:
        my_serial = thisFirewall.read_serial()
        if not my_serial:
            plogger.ELOG("Unable to retrieve box serial")
            sys.exit(0)

    if not key_file:
        privatekey = thisFirewall.read_barracuda_key()
        if not privatekey:
            plogger.ELOG("Unable to retrieve box private key")
            sys.exit(0)
    else:
        privatekey = read_key(key_file)  # if this fails we'll know when we try and use it
        if not privatekey:
            plogger.ELOG("Unable to use manually specified private key")
            sys.exit(0)

    if not mfg_version:
        mfg_version = thisFirewall.read_version()
        if not mfg_version:
            plogger.ELOG("Unable to retrieve box firmware version")
            sys.exit(0)

    if not output:
        output = thisFirewall.configOutput

    # got everything we need - so work out the UA to send
    user_agent = "{model} ({version})".format(model=thisFirewall.get_model(), version=mfg_version)

    if debug:
        plogger.ILOG("shared_secret: " + str(shared_secret))
        plogger.ILOG("my_serial: " + str(my_serial))
        plogger.ILOG("privatekey: " + str(privatekey))
        plogger.ILOG("mfg_version: " + str(mfg_version))
        plogger.ILOG("ZTD stop flag ({stop_flag}) exists: {stop_flag_exists}".format(stop_flag="{flag_dir}/ztdstopflag".format(flag_dir=thisFirewall.flagFileDirectory), stop_flag_exists=thisFirewall.has_stop_flag()))

    if do_check or (isinstance(thisFirewall, SSeries) and thisFirewall.has_revert_flag()):
        run_check()
    elif my_serial and mfg_version:
        prerequisite_checks(host, port, 60, debug, mfg_version)
        local_ip = thisFirewall.get_ip_address(host, port)
        url_nonce = 'https://{0}:{1}/api/v1/appliance/download/nonce'.format(host, port)
        cert_error, nonce = get_nonce(url_nonce, insecure)
        if cert_error and not insecure:
            cert_error, nonce = get_nonce(url_nonce, True)

            # Get the certificate so that we can report back the issuer
            ssl_socket = insecure_ssl_context.wrap_socket(sock=socket.socket(socket.AF_INET, socket.SOCK_STREAM))
            ssl_socket.connect((host, int(port)))
            # binary_form needs to be True, and the cert must be retrieved in DER format.
            # Otherwise, when cert validation is disabled, the certificate is not available
            # So we get the binary certificate and then shell to openssl to get the Issuer: field from it
            # since no Python libraries capable of processing a DER are present on the firewall
            cert_der = ssl_socket.getpeercert(binary_form=True)
            ssl_socket.close()
            get_cert_issuer = subprocess.Popen(["openssl", "x509", "-noout", "-issuer", "-outform", "pem", "-inform", "der"],
                                        stdin=subprocess.PIPE, stdout=subprocess.PIPE)
            cert_issuer, cert_stderr = get_cert_issuer.communicate(input=cert_der)

            payload = make_payload(my_serial, mfg_version, local_ip, certificateDetails=cert_issuer)
            url_ssl_error = 'https://{0}:{1}/api/v1/appliance/download/ssl'.format(host, port)
            report_cert_error(url_ssl_error, payload)
        elif nonce:
            payload = make_payload(my_serial, mfg_version, local_ip)
            if do_report or (isinstance(thisFirewall, SSeries) and thisFirewall.has_stats()):
                run_report(host, port, payload, insecure)
            else:
                run_zero_touch(host, port, http_port, output, payload, insecure, dry_run, debug, my_serial)
        else:
            plogger.ELOG("Unable to run: cannot retrieve nonce from server")
            sys.exit(0)
    else:
        plogger.ELOG("Unable to run: Private Key, Shared Secret, Serial Number and MFG_Version are not all available")
        sys.exit(0)


def usage():
    print __doc__


def prerequisite_checks(host, port, retry_interval, debug, mfg_version):
    # invalid dates will trigger the SSL interception warning, so we wait for NTP to fix up the time to be realistic
    while datetime.datetime.today().year < 2017:
        plogger.WLOG("Waiting for NTP sync, sleeping for {0} seconds".format(retry_interval))
        time.sleep(retry_interval)
    # wait for the web UI to settle
    while thisFirewall.webui_enabled() and thisFirewall.webui_change_pending():
        plogger.WLOG("The web UI is still starting up, sleeping for {0} seconds".format(retry_interval))
        time.sleep(retry_interval)

    # wait until we can successfully POST data to the ZTD service - SC2 networking can be slow to come up
    can_contact_ztd = False
    user_agent = "{model} ({version})".format(model=thisFirewall.get_model(), version=mfg_version)

    while not can_contact_ztd:
        try:
            urlopen(Request(url='https://{0}:{1}/connectivity'.format(host, port), data="", headers={'User-Agent': user_agent}), context=insecure_ssl_context, timeout=15)
            can_contact_ztd = True
        except URLError, u:
            if isinstance(u.reason, socket.error):
                plogger.FLOG("The ZTD portal could not be reached, sleeping for {0} seconds".format(retry_interval))
                if debug:
                    plogger.FLOG(str(u.reason))
                can_contact_ztd = False
                time.sleep(retry_interval)
            else:
                can_contact_ztd = True


def run_report(host, port, payload, insecure):
    url_stats = 'https://{0}:{1}/api/v1/appliance/download/reverted'.format(host, port)
    report_box_stats(url_stats, payload, insecure)
    thisFirewall.clear_stats()
    if isinstance(thisFirewall, SSeries):
        main()


def write_key(lines):
    if not lines:  # there is no key on this box
        return None
    else:
        f = tempfile.NamedTemporaryFile(delete=False)
        name = f.name
        for line in lines:
            f.write(line + "\n")

        f.close()
        return name


def read_key(keyfile):
    f = open(keyfile, "r")
    lines = f.read()
    f.close()

    return lines


def get_nonce(url_nonce, insecure):
    req = Request(url_nonce, data="",
                  headers={'User-Agent': user_agent, 'Content-Type': 'application/json', "charset": "UTF-8",
                           "Accept": "application/json"})

    try:
        if insecure:
            response = urlopen(req, context=insecure_ssl_context)
        else:
            response = urlopen(req)
    except URLError, u:
        if isinstance(u.reason, ssl.SSLError):
            plogger.ELOG("Certificate error connecting to the portal")
            checksum = "cert_error"
            return checksum, None
        else:
            plogger.ELOG("Unable to connect to the Zero Touch Service")
            reason = str(u.reason)
            if len(reason) < 1:
                reason = "Bad Request"
            plogger.ELOG(reason)
            return None, None
    except ssl.CertificateError:
        plogger.ELOG("Certificate error connecting to the portal")
        checksum = "cert_error"
        return checksum, None

    body = response.read()
    if len(body) > 0:
        jData = json.loads(body)
        nonce = jData['nonce']
        return None, nonce
    else:
        plogger.ELOG("Unable to retrieve nonce")


def run_check():
    check_duration = thisFirewall.process_revert_flag()

    # check for presence of backup
    got_backup = thisFirewall.has_backup()
    if not got_backup:
        plogger.WLOG("checking CC comms, but there is no backup available to revert to if revert is required")

    if check_duration > 0:
        if isinstance(thisFirewall, SSeries):
            is_connected = False
            plogger.ILOG("Collecting box stats")
        else:
            # start thread to monitor comms
            is_connected = thisFirewall.check_cc_connection(check_duration)

        if is_connected:
            plogger.ILOG("Connected, removing backup and exiting")
            thisFirewall.clear_revert_flag()
            if got_backup:
                thisFirewall.remove_backup()
            thisFirewall.finished_sound(success=True)
        else:
            if not isinstance(thisFirewall, SSeries):
                plogger.ILOG("CC connection failed, collecting box stats")
            stats = thisFirewall.collect_stats()
            thisFirewall.write_stats(stats)
            thisFirewall.clear_stop_flag()
            if got_backup:
                plogger.ILOG("Reapplying backup")
                thisFirewall.reapply_backup()
            else:
                plogger.ILOG("No backup to reapply")
            thisFirewall.finished_sound(success=False)

        plogger.ILOG("Post Configuration checks completed")
    else:
        plogger.ILOG("Post Configuration checks were not run")

    sys.exit(0)


def run_zero_touch(host, port, http_port, output, payload, insecure, dry_run, debug, serial):
    global nonce

    # go and do it
    url_config = 'https://{0}:{1}/api/v1/appliance/download/information'.format(host, port)
    url_download = 'https://{0}:{1}/api/v1/appliance/download'.format(host, port)
    url_status = 'https://{0}:{1}/api/v1/appliance/download/status'.format(host, port)
    url_nonce = 'https://{0}:{1}/api/v1/appliance/download/nonce'.format(host, port)

    should_stop = thisFirewall.has_stop_flag()

    while not thisFirewall.has_stop_flag():
        # check if ZT is still enabled every time we go round this loop
        if not thisFirewall.is_enabled():
            plogger.ILOG("Zero Touch is no longer enabled on this box")
            sys.exit()

        cert_error, new_nonce = get_nonce(url_nonce, insecure)
        if new_nonce:
            nonce = new_nonce
        else:
            plogger.ELOG("unable to refresh the nonce")
            sys.exit()

        checksum, retry_interval, verifySignature, revert_timer = check_for_config(url_config, payload, insecure)

        if debug:
            plogger.ILOG("Nonce: " + str(nonce))
            plogger.ILOG("checksum: " + str(checksum))
            plogger.ILOG("retry_interval: " + str(retry_interval))
            plogger.ILOG("verifySignature: " + str(verifySignature))
            plogger.ILOG("revert_timer: " + str(revert_timer))
            plogger.ILOG("url_config: " + str(url_config))
            plogger.ILOG("payload: " + str(payload))
            plogger.ILOG("insecure: " + str(insecure))

        if checksum:
            if revert_timer > 0:
                thisFirewall.make_backup()
                thisFirewall.write_revert_flag(revert_timer)

            report_status_update(url_status, payload, "downloading", "", insecure)
            configuration = download_config(url_download, payload, insecure)

            if configuration:
                report_status_update(url_status, payload, "downloaded", "", insecure)

                is_valid = validate_download(configuration, checksum)
                if is_valid:
                    plogger.ILOG("download is valid, installing")

                    report_status_update(url_status, payload, "checkSumSuccessful", "", insecure)
                    f = tempfile.NamedTemporaryFile(prefix="zt", suffix=".par", delete=False)
                    f.write(configuration)
                    f.flush()
                    f.close()

                    report_status_update(url_status, payload, "applying", "", insecure)
                    thisFirewall.install_config(f, output, dry_run)
                    os.unlink(f.name)

                    report_status_update(url_status, payload, "applied", "", insecure)

                    if not dry_run:
                        thisFirewall.reboot_box()
                else:
                    plogger.ELOG("Invalid download")
                    report_status_update(url_status, payload, "checkSumFailed", "", insecure)
                    thisFirewall.write_stop_flag()
            else:
                plogger.ELOG("cannot download from BNZT")
        else:
            plogger.ILOG("no config available to install, sleeping for {0} seconds ...".format(retry_interval))

        time.sleep(retry_interval)


def update_nonce_in_payload(payload):
    payload['nonce'] = nonce
    if privatekey:
        signed_data = sign_payload(payload)
    else:
        signed_data = payload['serial']

    payload["signedData"] = signed_data

    return payload


def make_payload(serial, mfg_version, local_ip, **kwargs):
    payload = {"serial": serial, "nonce": nonce}
    if privatekey:
        signed_data = sign_payload(payload)
    else:
        signed_data = serial

    if signed_data:
        payload["localIp"] = local_ip
        payload["signedData"] = signed_data
        payload["mfgVersion"] = mfg_version
        payload["version"] = script_version
        if kwargs is not None:
            for key, value in kwargs.iteritems():
                payload[key] = value
    else:
        plogger.ELOG("Unable to make payload")
        sys.exit(0)

    return payload


def sign_payload(data):
    value = data["serial"] + "-" + data["nonce"]

    signature = hmac.new(bytes(shared_secret).encode('utf-8'), bytes(value).encode('ascii'),
                         digestmod=hashlib.sha256).digest()
    encoded = base64.encodestring(signature).replace('\n', '')

    filename = write_key(privatekey)
    p1 = subprocess.Popen("echo -n {0}".format(bytes(encoded)).split(), stdout=subprocess.PIPE)
    p2 = subprocess.Popen("openssl dgst -sha256 -sign {0}".format(filename).split(), stdin=p1.stdout,
                          stdout=subprocess.PIPE)
    p1.stdout.close()  # Allow p1 to receive a SIGPIPE if p2 exits.
    signed_data, stderr = p2.communicate()
    os.unlink(filename)
    if stderr:
        plogger.ELOG("Unable to sign payload: " + stderr)
        time.sleep(60)
        sys.exit(0)
    else:
        return base64.b64encode(signed_data)


def validate_download(configuration, checksum):
    hashed_config = base64.b64encode(hashlib.sha256(configuration).digest())
    return hashed_config == checksum


def report_box_stats(url_stats, base_payload, insecure):
    global nonce
    payload = base_payload.copy()

    stats = thisFirewall.process_stats()

    payload["debug"] = base64.b64encode(stats)

    plogger.ILOG("Reporting box stats to ZTD Service")

    payload = update_nonce_in_payload(payload)
    data = json.dumps(payload)
    req = Request(url_stats, data=data,
                  headers={'User-Agent': user_agent, 'Content-Type': 'application/json', "charset": "UTF-8",
                           "Accept": "application/json"})

    try:
        if insecure:
            response = urlopen(req, context=insecure_ssl_context)
        else:
            response = urlopen(req)

        plogger.ILOG("Stats updated")

    except HTTPError, e:
        plogger.ELOG("Unable to report stats to server")
        # raise - don't raise this just log and carry on

    nonce = response.info().getheader('nonce')


def report_status_update(url_status, base_payload, status, message, insecure):
    global nonce
    payload = base_payload.copy()

    payload["action"] = status
    payload["message"] = message

    plogger.ILOG("Reporting status change to " + status)

    payload = update_nonce_in_payload(payload)
    data = json.dumps(payload)
    req = Request(url_status, data=data,
                  headers={'User-Agent': user_agent, 'Content-Type': 'application/json', "charset": "UTF-8",
                           "Accept": "application/json"})

    try:
        if insecure:
            response = urlopen(req, context=insecure_ssl_context)
        else:
            response = urlopen(req)
    except HTTPError, e:
        plogger.ELOG("Unable to report status to server")
        # raise - don't raise this just log and carry on

    nonce = response.info().getheader('nonce')
    plogger.ILOG("Status updated")


def report_cert_error(url_ssl_error, payload):
    plogger.ILOG("Reporting SSL error to BNZT portal ")

    data = json.dumps(payload)
    req = Request(url_ssl_error, data=data,
                  headers={'User-Agent': user_agent, 'Content-Type': 'application/json', "charset": "UTF-8",
                           "Accept": "application/json"})

    try:
        response = urlopen(req, context=insecure_ssl_context)
    except URLError, u:
        plogger.ELOG("Unable to report error to server")
        # raise - don't raise this just log and carry on

    # always sleep after reporting error
    # BNNGS-3071
    time.sleep(60)
    if isinstance(thisFirewall, SSeries):
        main()


def download_config(url_download, payload, insecure):
    global nonce
    plogger.ILOG("Downloading Configuration for serial " + payload["serial"])

    payload = update_nonce_in_payload(payload)
    data = json.dumps(payload)
    req = Request(url_download, data=data,
                  headers={'User-Agent': user_agent, 'Content-Type': 'application/json', "charset": "UTF-8",
                           "Accept": "application/octet-stream"})

    configuration = None

    try:
        if insecure:
            myResponse = urlopen(req, context=insecure_ssl_context)
        else:
            myResponse = urlopen(req)

        plogger.ILOG("Configuration downloaded from portal")
        nonce = myResponse.info().getheader('nonce')
        configuration = myResponse.read()
    except HTTPError, e:
        plogger.ELOG("Unable to retrieve configuration from server")
        # raise - don't raise this just log and carry on

    return configuration


def check_for_config(url_config, payload, insecure):
    global nonce

    checksum = None
    verifySignature = True
    retry_after = 60
    revert_timer = 0

    plogger.ILOG("Checking for Configuration for serial " + payload["serial"])

    payload = update_nonce_in_payload(payload)
    data = json.dumps(payload)

    req = Request(url_config, data=data,
                  headers={'User-Agent': user_agent, 'Content-Type': 'application/json', "charset": "UTF-8",
                           "Accept": "application/json"})

    try:
        if insecure:
            response = urlopen(req, context=insecure_ssl_context)
        else:
            response = urlopen(req)
    except URLError, u:
        if isinstance(u.reason, ssl.SSLError):
            plogger.WLOG("Certificate error connecting to the portal")
            checksum = "cert_error"
        else:
            plogger.ELOG("Unable to connect to the Zero Touch Service")
            reason = str(u.reason)
            if len(reason) < 1:
                reason = "Bad Request"
            plogger.ELOG(reason)
        return checksum, retry_after, False, 0

    body = response.read()
    interval = response.info().getheader('Retry-After')
    nonce = response.info().getheader('nonce')
    if interval:
        plogger.ILOG("setting retry interval to : " + interval)
        retry_after = int(interval)

    if len(body) > 0:
        jData = json.loads(body)
        if "checkSum" in jData:
            checksum = jData["checkSum"]
            plogger.ILOG("Configuration is available for download")
        else:
            plogger.ILOG("No Configuration available")

        if "applyConfigurationTimeout" in jData:
            revert_timer = jData["applyConfigurationTimeout"]

        if "verifySignature" in jData:
            verifySignature = jData["verifySignature"]

    else:
        plogger.ELOG("No response body on information call")

    return checksum, retry_after, verifySignature, int(revert_timer)


if __name__ == "__main__":
    main()
