#!/usr/bin/env python
"""
NetFoundry Router registration download
"""
import os
import sys
import time
import wget
import ssl
import requests
import subprocess
import reg_common

def cleanup_file(file_name):
    """
    Cleanup a file
    """
    try: 
        if os.path.exists(file_name): 
            os.remove(file_name)
    except OSError:
        print("ERROR: Unable to remove file ", file_name)    

def compare_dates(file_name):
    """
    Compare current date to file creation time, return True if it's older an 24hrs
    """
    current_time_in_seconds = time.time()
    if os.stat(file_name).st_mtime < current_time_in_seconds - 86400:
        return True
    return False

def download_file(source_url):
    """
    Download file
    """
    try:
        ssl._create_default_https_context = ssl._create_unverified_context
        print("Downloading latest version before executing")
        wget.download(source_url, out="/opt/netfoundry/.zt-upg")
        print(" ")
        os.chmod("/opt/netfoundry/.zt-upg", 0o755)
    except Exception as e:
        print("Error: Unable to download binaries: ", e)
        sys.exit(1)


def root_check():
    """
    Check to see if this is running as root
    """
    if os.geteuid() >= 1:
        print("ERROR: This script must be run with root privileges, please use sudo or run as root")
        sys.exit(1)

def main():
    """
    Main logic
    """
    __version__ = '1.0.0'
    # change log
    # 1.0.0 - initial release

    # define static variables
    reg_file_path = "/opt/netfoundry/.zt-upg"

    if reg_common.arm_check():
       artifactory_url = "https://netfoundry.jfrog.io/artifactory/router-registration/zt-upg/release/linux_arm32/latest/zt-upg"
    else:
       artifactory_url = "https://netfoundry.jfrog.io/artifactory/router-registration/zt-upg/release/linux/latest/zt-upg"
    update = False
    # run root check
    root_check()

    # only compare if file exists
    if os.path.exists(reg_file_path):

        # only update if it's older than 24hrs
        file_is_too_old = compare_dates(reg_file_path)
        if file_is_too_old:
            update = True
    else:
        update = True

    # only download if update is needed
    if update:
        cleanup_file(reg_file_path)
        download_file(artifactory_url)

    # run script
    sub_command = [reg_file_path] + sys.argv[1:]
    subprocess.run(sub_command)
  

# main
if __name__ == '__main__':
    main()
