#Importing all the libraries
import os
import subprocess
import shutil
import plistlib


print("========================================================")
print("Automating the Mac Agent Creation")

version = "2.5.5.1"

clientName = "testPoorna"

folder_path = '/Users/administrator/Desktop/AppContents/pythonMac/'+version +'/'

new_folder_path = os.path.join(folder_path, clientName)

parablu_epaApp = '/Users/administrator/Desktop/AppContents/pythonMac/baseagent/Parablu_EPA.app'
loginType = "nonsilent"

clientFullyDomain = 'test-poorna.parablu.com'

os.makedirs(new_folder_path)


shutil.copytree(parablu_epaApp, os.path.join(new_folder_path, os.path.basename(parablu_epaApp)))

print("File Copied Successfully")

fileAppDirectory = '/Users/administrator/Desktop/AppContents/pythonMac/'+ version+'/'+clientName+'/'+'Parablu_EPA.app'
#
##To Remove the signature of the app
subprocess.run(['codesign', '--remove-signature', fileAppDirectory])
print("Successfully the signature is removed")

#
wlProp = os.path.join(fileAppDirectory, 'Contents/app/ParaBlu/WL.properties')

InfoPlist = os.path.join(fileAppDirectory, 'Contents/Info.plist')
#
##Defining the properties to modify in the WL.properties
## Define the properties to modify and their new values
new_properties = {
    'BluSync-Version-Label': version,
    'login-type': loginType,
    'Cloud-Name': clientName,
    'Main-EBMS-domain': clientFullyDomain
}

print("The below are the new properties that will be added to the WL.properties")

## Read the existing properties from the file
existing_properties = {}
#
with open(wlProp, 'r') as f:
    for line in f:
        if '=' in line:
            key, value = line.strip().split('=', 1)
            existing_properties[key.strip()] = value.strip()

# Modify the existing properties with the new values
for key, value in new_properties.items():
    existing_properties[key] = value

# Write the modified properties back to the file
with open(wlProp, 'w') as f:
    for key, value in existing_properties.items():
        f.write(f'{key} = {value}\n')


print("successfully modified the WL properties")

 # Open the info.plist file
with open(InfoPlist, 'rb') as fp:
    plist = plistlib.load(fp)

print("The info plist of read")

# Modify the values
plist['CFBundleShortVersionString'] = version
plist['CFBundleVersion'] = version
SUFeed =  'https://'+clientFullyDomain+'/downloads/update.xml'
plist['SUFeedURL'] = SUFeed # Save the modified plist back to the file with open('Contents/info.plist', 'wb') as fp: plistlib.dump(plist, fp)

print("Modifying the details")

with open(InfoPlist, 'wb') as fp:
    plistlib.dump(plist, fp)

print("Successfully Modified")


identity = "Developer ID Application: ParaBlu Systems Private Limited"
entitlements_path = "/Users/administrator/Desktop/AppContents/jpackage/entitlements.plist"
args = [
    "codesign",
    "--timestamp",
    "--entitlements",entitlements_path,
    "--options=runtime",
    "--deep",
    "-s", identity,
    fileAppDirectory,
]

result = subprocess.run(args,capture_output = True)

if result.returncode!=0:
    print(result.srderr.decode("utf-8"))
else:
    print("Code Signing was successfull")

print("Will be verifying whether the code sign was successfull")
argsVerify = [
    "codesign",
    "--verify",
    "--deep",
    "--strict",
    "--verbose",
    fileAppDirectory,
]

resultVer = subprocess.run(argsVerify,capture_output = True)

print("Verifying the signature")
if resultVer.returncode==0:
    print("Code Signing was successfull")
else:
    print(resultVer.stderr.decode('utf-8'))


##Spctl Command

argsSpctl = [
              "spctl",
              "-a",
              "-t",
              "exec",
              "-vvv",
              fileAppDirectory,
              ]

resultSpctl = subprocess.run(argsSpctl,capture_output = True)

if "accepted" in resultSpctl.stdout.decode('utf-8'):
    print("Code Signature Check Successfull")
else:
    print(resultSpctl.stderr.decode('utf-8'))
