#!/usr/bin/python

import os
import shutil
import sys
import platform

import syslog
syslog.openlog("crypt-preinstall")

def fail(message, exit=True):
    syslog.syslog(syslog.LOG_ALERT, message)
    print(message)
    if exit:
        sys.exit(1)

def move_old_plist():
    old_plist = '/private/var/root/recovery_key.plist'
    new_plist = '/private/var/root/crypt_output.plist'
    if os.path.exists('/private/var/root/recovery_key.plist'):
        # We have an old recovery key, move it to the new location
        try:
            shutil.move(old_plist, new_plist)
        except:
            fail('Could not move old plist to new location')

def remove_old_app():
    # remove old installdir
    old_install_dir = '/usr/local/crypt'
    if os.path.exists(old_install_dir):
        shutil.rmtree(old_install_dir)


def getOsVersion(only_major_minor=True, as_tuple=False):
    """Returns an OS version.
    Args:
      only_major_minor: Boolean. If True, only include major/minor versions.
      as_tuple: Boolean. If True, return a tuple of ints, otherwise a string.
    """
    os_version_tuple = platform.mac_ver()[0].split('.')
    if only_major_minor:
        os_version_tuple = os_version_tuple[0:2]
    if as_tuple:
        return tuple(map(int, os_version_tuple))
    else:
        return '.'.join(os_version_tuple)


def os_check_abort():
    # abort if less than 10.12
    version_tup = getOsVersion(as_tuple=True)
    if version_tup[1] < 12:
        fail('ERROR! Crypt 3.0 does not support macOS versions before 10.12..',
             exit=False)
        fail('ERROR! Please use a previous version of Crypt..')


def main():
    os_check_abort()
    move_old_plist()
    print('crypt-preinstall successful...')

if __name__ == '__main__':
    main()
