#!/usr/bin/python

import base64
import os
import sys
import subprocess

import re
sys.path.append('/usr/local/munki')

from munkilib import fetch
from munkilib import munkicommon
#from munkilib import keychain
from munkilib import prefs
from munkilib import display

#keychain_obj = keychain.MunkiKeychain()

stream = os.popen("openssl x509 -in /Library/Managed\ Installs/ssl/munki.pem -noout -fingerprint | sed -e 's/://g' | awk -F= {'print $2'} | tr '[:upper:]' '[:lower:]'")
fingerprint = stream.read().strip()

stream = os.popen("openssl x509 -in /Library/Managed\ Installs/ssl/munki.pem -noout -subject | sed -e 's/subject= //'")
subject = stream.read().strip()

fullURL = munkicommon.pref('SoftwareRepoURL') + '/MTM.reconfigure/get_info.php?fingerprint=' + fingerprint + '&subject=' + base64.b64encode(subject)

fetch.getResourceIfChangedAtomically(fullURL,'/Library/Managed Installs/onboardinfo')

stream = os.popen("ioreg -c IOPlatformExpertDevice -d 2 | awk -F\\\" '/IOPlatformSerialNumber/{print $(NF-1)}'")
serial_number = stream.read().strip()
extraheader = 'Authorization: Basic ' + base64.b64encode(serial_number + ':' + fingerprint)

if munkicommon.pref('UseClientCertificate'):
      subprocess.check_output(['defaults','write','/Library/Preferences/ManagedInstalls.plist','AdditionalHttpHeaders','-array',extraheader])
      subprocess.check_output(['defaults','write','/Library/Preferences/ManagedInstalls.plist','UseClientCertificate','-bool','false'])
      subprocess.check_output(['defaults','delete','/Library/Preferences/ManagedInstalls.plist','ClientCertificatePath'])
      subprocess.check_output(['defaults','delete','/Library/Preferences/ManagedInstalls.plist','ClientKeyPath'])

old_pref_file = '/var/root/Library/Preferences/ManagedInstalls.plist'
if os.path.exists(old_pref_file):
      with open(old_pref_file) as file:
            if 'AdditionalHttpHeaders' in file.read():
                  subprocess.check_output(['defaults','delete',old_pref_file,'AdditionalHttpHeaders'])

f = open('/Library/Managed Installs/onboardinfo')

params = {}
for line in f:
      paramsraw = re.search('(^[^:]*):\s(.*)',line)
      if paramsraw is not None :
        params[paramsraw.group(1)] = paramsraw.group(2)

f.close()

if params['rename'] == '1':
      try:
            compname = subprocess.check_output(['scutil','--get','ComputerName']).strip('\n')
      except:
            compname = ''

      try:
            lhostname = subprocess.check_output(['scutil','--get','LocalHostName']).strip('\n')
      except:
            lhostname = ''

      try:
            fullhostname = subprocess.check_output(['scutil','--get','HostName']).strip('\n')
      except:
            fullhostname = ''

      if compname != params['name']:
            res = subprocess.check_output(['scutil','--set','ComputerName',params['name']])
      if lhostname != params['name']:
            res = subprocess.check_output(['scutil','--set','LocalHostName',params['name']])

      if fullhostname != params['name']:
            res = subprocess.check_output(['scutil','--set','HostName',params['name']])

if munkicommon.pref('ClientIdentifier') != params['clientidentifier']:
      subprocess.check_output(['defaults','write','/Library/Preferences/ManagedInstalls.plist','ClientIdentifier',params['clientidentifier']])


if params['SoftwareRepoURL'] != '':
      rememberURL = munkicommon.pref('SoftwareRepoURL');
      if munkicommon.pref('SoftwareRepoURL') != params['SoftwareRepoURL']:
            display.display_info('Cur SoftwareRepoURL is set to %s' % rememberURL)
            display.display_info('New SoftwareRepoURL is set to %s' % params['SoftwareRepoURL'])
            display.display_info('Updating SoftwareRepoURL and testing connection to repo')
            #sys.stderr.write("Cur SoftwareRepoURL is set to " + rememberURL + "\n")
            #sys.stderr.write("New SoftwareRepoURL is set to " + params['SoftwareRepoURL'] + "\n")
            #sys.stderr.write("Up for a change!\n")
            try: 
                  subprocess.check_output(['defaults','write','/Library/Preferences/ManagedInstalls.plist','SoftwareRepoURL',params['SoftwareRepoURL']])
                  certhash = keychain.pem_cert_sha1_digest('/Library/Managed Installs/ssl/munki.pem')
                  output = keychain.security('set-identity-preference','-s',params['SoftwareRepoURL'] + '/','-Z',certhash,'/Library/Managed Installs/Keychains/munki.keychain');
                  prefs.reload_prefs()
                  newURL = params['SoftwareRepoURL'] + '/MTM.reconfigure/get_info.php'
                  display.display_info('Trying %s' % newURL)
                  #sys.stderr.write( "Trying " + newURL + "\n")
                  fetch.getResourceIfChangedAtomically(newURL,'/Library/Managed Installs/onboardinfo2')
                  display.display_info('Connection successful. Repo URL Changed')
                  #sys.stderr.write("REPO URL Changed\n");
            except:
                  display.display_error('Repo URL change DID NOT WORK. Reverting to previous SoftwareRepoURL')
                  #sys.stderr.write("Change DID NOT WORK!\n")
                  subprocess.check_output(['defaults','write','/Library/Preferences/ManagedInstalls.plist','SoftwareRepoURL',rememberURL])

