url = "https://script-downloads.itarian.com/MacOS_CCS/CCS_2.4.4.974.dmg"

import ssl
from urllib import request
import os
import shutil

file_dir= "/private/tmp/temp_CCS"

if not os.path.exists(file_dir):
    os.makedirs(file_dir)

Down_path=file_dir
fileName = url.split('/')[-1]
DownTo = os.path.join(Down_path, fileName)

def ecmd(command):   
    from subprocess import Popen, PIPE

    obj = Popen(command, shell = True, stdout = PIPE, stderr = PIPE)
    out, err = obj.communicate()
    ret=obj.returncode
    return ret,out,err

def downloadFile(DownTo, fromURL):
    headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36'}
    context = ssl._create_unverified_context()
    Rq = request.Request(fromURL, headers=headers)
    req = request.urlopen(Rq,context=context)
    try:
        with open(DownTo, 'wb') as f:
            while True:
                chunk = req.read(100*1000*1000)
                if chunk:
                    f.write(chunk)
                else:
                    break
        if os.path.isfile(DownTo):
            return '{} - {}KB'.format(DownTo, os.path.getsize(DownTo)/1024)
		
    except:
        return 'Please Check URL or Download Path!'

def install_CCS():

    print(downloadFile(DownTo,url))

    bash_script = """#!/bin/bash

hdiutil attach -nobrowse %s
sudo "/volumes/COMODO-CS/Install COMODO Client - Security.app/Contents/MacOS/Install COMODO Client - Security" --silent
hdiutil detach -force -quiet /volumes/COMODO-CS
    """%(DownTo)

    script_path = Down_path + "/install_CCS.sh"

    with open(script_path,'w') as f:
        f.write(bash_script)

    ret,out,err = ecmd('sh "%s"'%(script_path))
    if ret==0:
        if out:
            print(out.decode('utf-8').strip())
        else:
            print(ret)
    else:
        if err:
            print(err.decode('utf-8').strip())
        else:
            print(ret)
    
    shutil.rmtree(Down_path,ignore_errors=True)

MacOS_version = os.popen("sw_vers -productVersion").read()

if 12 > int(MacOS_version.split('.')[0]):
    print("MacOS version: %s"%(MacOS_version))
    print("MacOS version is less than 12.x. installing CCS 2.4")
    install_CCS()
else:
    print("MacOS version: %s"%(MacOS_version))
    print("MacOS version is not less than 12.x")

