#!/usr/bin/python
"""
Riptide Auth upgrade script
"""
import logging
import os
import sys
import syslog
import re

import isi.auth_util as auth_util
import isi.auth as auth
from isi.app.lib import safelockfile
from isi.app.lib.confParser import ConfParser
import isi.config as iconf
import isi.config.krb5 as krb5cfg
import isi.config.zone as zonecfg
import isi.gconfig as gcfg
import isi.sys.version as sysver


IFS_BACKUP_PATH = "/ifs/.ifsvar/tmp"
LOG_FILE = os.path.join(IFS_BACKUP_PATH, "riptide-auth-upgrade.log")
AUTH_UPGRADE_LOCKFILE = os.path.join(IFS_BACKUP_PATH, "riptide-auth-upgrading")
AUTH_UPGRADED_PART1_FILE = os.path.join(IFS_BACKUP_PATH, "riptide-auth-upgrade-p1-complete")
AUTH_UPGRADED_PART2_FILE = os.path.join(IFS_BACKUP_PATH, "riptide-auth-upgrade-p2-complete")
AUTH_UPGRADED_PART3_FILE = os.path.join(IFS_BACKUP_PATH, "riptide-auth-upgrade-p3-complete")
AUTH_UPGRADED_PART4_FILE = os.path.join(IFS_BACKUP_PATH, "riptide-auth-upgrade-p4-complete")

ACLPOLICIES_SYSCTL = "efs.bam.acl_policies"
SYSCTL_OVERRIDE_CONF = "/etc/mcp/override/sysctl.conf"
SYSCTL_GCFG_PATH = "sysctls.entries"

LWREG_PROVIDER_PREFIX = "registry.Services.lsass.Parameters.Providers"
LWREG_ZONE_PREFIX = "registry.Services.lsass.Parameters.Zones"
LWREG_ALL_AUTH_PROVIDERS_KEY = "AllAuthProviders"
LWREG_CACHE_ENTRY_EXPIRY_KEY = "CacheEntryExpiry"
LWREG_GROUPNET_KEY = "Groupnet"
LWREG_PROVIDER_LIST_KEY = "ProviderList"
LWREG_ZONE_ID_KEY = "ZoneId"
PSTORE_INSTANCE_NAME_KEY = "InstanceName"
PSTORE_DNS_DOMAIN_NAME_KEY = "DnsDomainName"

LWREG_PERMITTED_ENCTYPES = "krb5cfg.defaults.permitted_enctypes"
LWREG_PREFERRED_ENCTYPES = "krb5cfg.defaults.preferred_enctypes"
LWREG_DEFAULT_TKT_ENCTYPES = "krb5cfg.defaults.default_tkt_enctypes"
LWREG_DEFAULT_TGS_ENCTYPES = "krb5cfg.defaults.default_tgs_enctypes"

KRB5_DEFAULT_ENCTYPES = ['RC4-HMAC', 'DES-CBC-MD5', 'DES-CBC-CRC']

KRB5_CFG = "/etc/krb5.conf"
LIKEWISE_KRB5_CFG = "/etc/likewise-krb5-ad.conf"
LIKEWISE_KRB5_CFG_TMP = "/etc/likewise-krb5-ad.conf.tmp"
KRB5_CFG_TGS_ENCTYPES = "default_tgs_enctypes"
KRB5_CFG_TKT_ENCTYPES = "default_tkt_enctypes"
KRB5_CFG_PERMITTED_ENCTYPES = "permitted_enctypes"
KRB5_CFG_PREFERRED_ENCTYPES = "preferred_enctypes"
KRB5_CFG_AES256 = "AES256-CTS"
KRB5_CFG_AES128 = "AES128-CTS"
KRB5_CFG_RC4 = "RC4-HMAC"
KRB5_CFG_DES_MD5 = "DES-CBC-MD5"
KRB5_CFG_DES_CRC = "DES-CBC-CRC"

ISI_PRIV_ISCSI = "ISI_PRIV_ISCSI"
DEFAULT_ROLES = ['AuditAdmin', 'BackupAdmin', 'SecurityAdmin',
            'SystemAdmin', 'VMwareAdmin']

#MAX_COMMIT_RETRIES = 100
MAX_COMMIT_RETRIES = 2
SYSTEM_ZONE = "System"
DEFAULT_GROUPNET = 1
DEFAULT_ACLPOLICIES_SYSCTL = 65796 # pre Riptide default
DEFAULT_CACHE_ENTRY_EXPIRY = 14400 # 4H

LOGGER = logging.getLogger("riptide_auth_upgrade")

# Returns a list of encryptions from the input encryption string list that are
# not in the default list.
def krb5_cfg_get_new_encryptions(encryption_string):
        encryption_list = re.split(',| ', encryption_string.upper())
        added_encryptions = [x for x in encryption_list if x and x not in KRB5_DEFAULT_ENCTYPES]
        return added_encryptions

def krb5_cfg_add_new_encryptions(option, new_encryptions):
        prefix = option[0 : option.find('=')  + 1]
        encryption_string = option[option.find('=') + 1: -1]
        encryption_list = re.split(',| ', encryption_string.upper())
        encryption_list = [x for x in encryption_list if x]
        new_option = prefix
        for x in new_encryptions:
                if x not in encryption_list:
                        new_option = new_option + ' ' + x
        for x in encryption_list:
                new_option = new_option + ' ' + x
        new_option = new_option + '\n'
        return new_option

def krb5_cfg_to_likewise_ad_cfg(main_cfg):
        """
        In Moby, with NFS moved into userspace as a likewise process it now uses the
        likewise-krb5-ad.conf instead of the krb5.conf. Solution for now is move the
        any added encryptions in the krb5.conf to the likewise-krb5-ad.conf. We will
        not remove any encryption types from the likewise-krb5-ad.conf as that may
        cause some compatability issues.
        """

        krb5_ad_conf = open(LIKEWISE_KRB5_CFG, 'r')
        config = list(krb5_ad_conf)
        krb5_ad_conf.close()
        new_config = list()
        if not config:
            return

        new_permitted_enctypes = krb5_cfg_get_new_encryptions(main_cfg.read(LWREG_PERMITTED_ENCTYPES))
        new_preferred_enctypes = krb5_cfg_get_new_encryptions(main_cfg.read(LWREG_PREFERRED_ENCTYPES))
        new_default_tkt_types = krb5_cfg_get_new_encryptions(main_cfg.read(LWREG_DEFAULT_TKT_ENCTYPES))
        new_default_tgs_types = krb5_cfg_get_new_encryptions(main_cfg.read(LWREG_DEFAULT_TGS_ENCTYPES))

        for option in config:
            new_option = option
            stripped_line = new_option.strip()
            if not stripped_line: # ignore empty lines
                new_config.append(new_option)
                continue
            if stripped_line.startswith(('#',';')): # ignore comments
                new_config.append(new_option)
                continue
            if '=' not in option: #ignore mis-formatted lines
                new_config.append(new_option)
                continue
            if KRB5_CFG_TGS_ENCTYPES in option:
                new_option = krb5_cfg_add_new_encryptions(option, new_default_tgs_types)
            if KRB5_CFG_TKT_ENCTYPES in option:
                new_option = krb5_cfg_add_new_encryptions(option, new_default_tkt_types)
            if KRB5_CFG_PERMITTED_ENCTYPES in option:
                new_option = krb5_cfg_add_new_encryptions(option, new_permitted_enctypes)
            if KRB5_CFG_PREFERRED_ENCTYPES in option:
                new_option = krb5_cfg_add_new_encryptions(option, new_preferred_enctypes)
            new_config.append(new_option)
        new_krb5_ad_conf = open(LIKEWISE_KRB5_CFG_TMP, 'w')
        for x in new_config:
            new_krb5_ad_conf.write(x)
        new_krb5_ad_conf.close()
        os.rename(LIKEWISE_KRB5_CFG_TMP, LIKEWISE_KRB5_CFG)

def krb5_cfg_add_aes(main_cfg, path):
    if not main_cfg.at_default(path):
        enctypes = main_cfg.read(path)
        if KRB5_CFG_AES128 not in enctypes:
            enctypes = KRB5_CFG_AES128 + " " + enctypes
        if KRB5_CFG_AES256 not in enctypes:
            enctypes = KRB5_CFG_AES256 + " " + enctypes
        main_cfg.write(path, enctypes)

def krb5_cfg_aes_upgrade(main_cfg):
        """
        In Riptide AES128 and AES256 encryption support was added which need
        to be added in the likewise-krb5-ad.conf file and the krb5 config if
        it had been previously edited.. The conf file is preserved on upgrade,
        as the user may have modified it so we need to manually go through the
        file and add the new encryptions to the list.
        """

        # Add AES encryption to the krb5 gcfg if the options have been modified
        krb5_cfg_add_aes(main_cfg, LWREG_PERMITTED_ENCTYPES)
        krb5_cfg_add_aes(main_cfg, LWREG_PREFERRED_ENCTYPES)
        krb5_cfg_add_aes(main_cfg, LWREG_DEFAULT_TKT_ENCTYPES)
        krb5_cfg_add_aes(main_cfg, LWREG_DEFAULT_TGS_ENCTYPES)

        # Add AES encryption to the likewise-krb5-ad.conf
        krb5_ad_conf = open(LIKEWISE_KRB5_CFG, 'r')
        config = list(krb5_ad_conf)
        krb5_ad_conf.close()
        new_config = list()
        if not config:
            return
        for option in config:
            new_option = option
            stripped_line = new_option.strip()
            if not stripped_line: # ignore empty lines
                new_config.append(new_option)
                continue
            if stripped_line.startswith(('#',';')): # ignore comments
                new_config.append(new_option)
                continue
            if '=' not in option: #ignore mis-formatted lines
                new_config.append(new_option)
                continue
            if (KRB5_CFG_TGS_ENCTYPES in option or
                KRB5_CFG_TKT_ENCTYPES in option or
                KRB5_CFG_PERMITTED_ENCTYPES in option or
                KRB5_CFG_PREFERRED_ENCTYPES in option):
                prefix = option[0 : option.find('=') + 1]
                encryptions = option[option.find('=') + 1 : -1]
                encryption_list = re.split(',| ', encryptions)
                encryption_list = [x for x in encryption_list if x]
                if KRB5_CFG_AES128 not in encryption_list:
                    encryption_list.insert(0, KRB5_CFG_AES128)
                if KRB5_CFG_AES256 not in encryption_list:
                    encryption_list.insert(0, KRB5_CFG_AES256)
                new_option = prefix
                for x in encryption_list:
                    new_option += ' ' + x
                new_option += '\n'
            new_config.append(new_option)
        new_krb5_ad_conf = open(LIKEWISE_KRB5_CFG_TMP, 'w')
        for x in new_config:
            new_krb5_ad_conf.write(x)
        new_krb5_ad_conf.close()
        os.rename(LIKEWISE_KRB5_CFG_TMP, LIKEWISE_KRB5_CFG)

def list_zones():
    """
    Get a list of zone names
    """
    return zonecfg.list_zones()

def acl_policies_sysctl_upgrade(main_cfg):
    """
    In Riptide two changes were made to ACL policies.  First, the default
    ACL policy setting for 'group_owner_inheritance' option changed from
    'native' to 'creator'.  When upgrading clusters we want to maintain the
    previous behavior therefore if no acl_polices sysctl override exists
    we should set one using the 'old' pre-upgrade defaults.  Second, the
    acl_policies sysctl override was moved from mcp's sysctl.conf override
    file to gconfig.  If we find an acl_policies sysctl override in mcp's
    sysctl.conf override file then we should move it to gconfig.  Notice that
    these upgrade cases are mutually exclusive.
    """
    conf = ConfParser(SYSCTL_OVERRIDE_CONF)
    if ACLPOLICIES_SYSCTL not in conf.values:
        acl_policies_value = str(DEFAULT_ACLPOLICIES_SYSCTL)
    else:
        acl_policies_value = conf.values[ACLPOLICIES_SYSCTL]

    entries = main_cfg.read(SYSCTL_GCFG_PATH)
    found = False
    for i in xrange(len(entries)):
            if isinstance(entries[i],dict) and  \
            'name' in entries[i].keys() and     \
            entries[i]['name'] == ACLPOLICIES_SYSCTL:
                    found = True
    if not found:
            entries.append({"name": ACLPOLICIES_SYSCTL, "value": acl_policies_value})
    main_cfg.write(SYSCTL_GCFG_PATH, entries)

def acl_policies_sysctl_upgrade_cleanup():
    """
    Cleanup sysctl override file, removing ACL policies system if found.
    """
    conf = ConfParser(SYSCTL_OVERRIDE_CONF)
    if ACLPOLICIES_SYSCTL in conf.values:
        del conf.values[ACLPOLICIES_SYSCTL]
        conf.write_and_rename(os.path.join(IFS_BACKUP_PATH,
            "%s.old" % SYSCTL_OVERRIDE_CONF))

def build_provider_summary(main_cfg):
    """
    Build a list of auth providers in lsass LoadProvider order.  Note:
    lsa-local-provider is last in the list because to copy how lsass loads
    the local provider for zones with all_auth_providers enabled.
    """
    key_to_type_map = {"ActiveDirectory": "lsa-activedirectory-provider",
            "File": "lsa-file-provider",
            "Ldap": "lsa-ldap-provider",
            "Nis": "lsa-nis-provider",
            "Krb5": "lsa-krb5-provider",
            "Local": "lsa-local-provider"}

    # fetch provider auth provider LoadOrder
    path = "%s.LoadOrder" % LWREG_PROVIDER_PREFIX
    load_order = main_cfg.read(path)
    # Nss could have still been in load order due to
    # bug in isi_classic that allowed it
    # Make sure that we do not use it.
    if "Nss" in load_order:
        load_order.remove("Nss")
        main_cfg.write(path, load_order)

    if "Local" in load_order:
        load_order.remove("Local")
        load_order.append("Local")

    # gather a list of all providers
    provider_summary = []
    for key in load_order:
        # the system file provider is a static key, just add it
        if key == "File":
            provider_summary.append("lsa-file-provider:System")
        # lookup dynamic providers
        path = "%s.%s.Instance._key" % (LWREG_PROVIDER_PREFIX, key)
        instances = main_cfg.read(path)
        for instance in instances:
            provider_summary.append("%s:%s" % (key_to_type_map[key],
                instance["_name"]))

    return provider_summary

def generate_provider_list(provider_summary, zone):
    """
    Given a provider summary and a zone name, build a list of auth providers
    equivalent to if the zone had all_auth_providers enabled.
    """
    provider_list = []
    for provider in provider_summary:
        if provider.startswith("lsa-local-provider") and \
                provider != ("lsa-local-provider:%s" % zone):
            continue
        provider_list.append(provider)
    return provider_list

def zone_all_auth_providers_upgrade(main_cfg):
    """
    In Riptide access zones no longer support the 'all-auth-providers'
    field. To maintain behavior this function searches for any zone with
    'all-auth-providers' enabled and updates the zone's provider list to
    be equivalent to how lsass loads providers for zone's with
    'all-auth-providers' enabled.
    """

    # gather a list of all providers
    provider_summary = build_provider_summary(main_cfg)

    # system zone is special
    path = "%s.System" % LWREG_ZONE_PREFIX
    instance = main_cfg.read(path)
    if instance[LWREG_ALL_AUTH_PROVIDERS_KEY] == 1:
        instance[LWREG_PROVIDER_LIST_KEY] = generate_provider_list(
                provider_summary, "System")
        main_cfg.write(path, instance)

    # all other zones are stored in dynamic keys
    path = "%s._key" % LWREG_ZONE_PREFIX
    instances = main_cfg.read(path)
    for instance in instances:
        all_auth_providers = False
        # look up all-auth-providers entry
        for entry in instance["_dword"]:
            if entry["_name"] == LWREG_ALL_AUTH_PROVIDERS_KEY and \
                    entry["value"] == 1:
                all_auth_providers = True
                break
        if not all_auth_providers:
            continue
        provider_list = generate_provider_list(provider_summary,
                instance["_name"])
        # look up the provider list
        for entry in instance["_multi_sz"]:
            if entry["_name"] == LWREG_PROVIDER_LIST_KEY:
                entry["value"] = provider_list
                break
        else:
            instance["_multi_sz"].append({"_name": LWREG_PROVIDER_LIST_KEY,
                "value": provider_list})
    main_cfg.write(path, instances)

def zone_groupnet_upgrade(main_cfg):
    """
    Zones pre-riptide had no knowledge of groupnets.  We need to set
    each zone's groupnet to groupnet0.  Note the system zone's config schema
    already sets groupnet to groupnet0 so we don't have to worry about it.
    """
    path = "%s._key" % LWREG_ZONE_PREFIX
    instances = main_cfg.read(path)
    for instance in instances:
        for entry in instance["_dword"]:
            if entry["_name"] == LWREG_GROUPNET_KEY:
                entry["value"] = DEFAULT_GROUPNET
                break
        else:
            instance["_dword"].append({"_name": LWREG_GROUPNET_KEY,
                "value": DEFAULT_GROUPNET})
    main_cfg.write(path, instances)

def auth_provider_groupnet_upgrade(main_cfg):
    """
    Auth providers pre-riptide had no knowledge of groupnets.  We need to set
    each providers groupnet to groupnet0.
    """
    for key in ("ActiveDirectory", "Krb5", "Ldap", "Nis"):
        path = "%s.%s.Instance._key" % (LWREG_PROVIDER_PREFIX, key)
        instances = main_cfg.read(path)
        for instance in instances:
            for entry in instance["_dword"]:
                if entry["_name"] == LWREG_GROUPNET_KEY:
                    entry["value"] = DEFAULT_GROUPNET
                    break
            else:
                instance["_dword"].append({"_name": LWREG_GROUPNET_KEY,
                    "value": DEFAULT_GROUPNET})
        main_cfg.write(path, instances)

def cache_entry_expiry_upgrade(main_cfg):
    """
    cache_entry_expiry changed from per-provider to per-zone.  We need to
    iterate over external provider instances finding the largest
    cache_entry_expiry value and use that for all zones.
    """
    cache_entry_expiry = None
    for key in ("ActiveDirectory", "Krb5", "Ldap", "Nis"):
        path = "%s.%s.Instance._key" % (LWREG_PROVIDER_PREFIX, key)
        instances = main_cfg.read(path)
        for instance in instances:
            for entry in instance["_dword"]:
                if entry["_name"] == LWREG_CACHE_ENTRY_EXPIRY_KEY and \
                        entry["value"] > cache_entry_expiry:
                    cache_entry_expiry = entry["value"]
                    break
    if cache_entry_expiry is None:
        cache_entry_expiry = DEFAULT_CACHE_ENTRY_EXPIRY

    # system zone is special
    path = "%s.System" % LWREG_ZONE_PREFIX
    instance = main_cfg.read(path)
    instance[LWREG_CACHE_ENTRY_EXPIRY_KEY] = cache_entry_expiry
    main_cfg.write(path, instance)
    auth_util.idmap_set_expiry(cache_entry_expiry, zid=auth_util.SYSTEM_ZONE)

    # all other zones are stored in dynamic keys
    path = "%s._key" % LWREG_ZONE_PREFIX
    instances = main_cfg.read(path)
    for instance in instances:
        # lookup zone id
        zid = None
        for entry in instance["_dword"]:
            if entry["_name"] == LWREG_ZONE_ID_KEY:
                zid = entry["value"]
                break
        # lookup field
        for entry in instance["_dword"]:
            if entry["_name"] == LWREG_CACHE_ENTRY_EXPIRY_KEY:
                entry["value"] = cache_entry_expiry
                break
        else:
            instance["_dword"].append({"_name": LWREG_CACHE_ENTRY_EXPIRY_KEY,
                "value": cache_entry_expiry})
        if zid is not None:
            auth_util.idmap_set_expiry(cache_entry_expiry, zid=zid)
    main_cfg.write(path, instances)

def ad_multi_instances_upgrade(pstore_cfg):
    """
    For AD multi-instance support an InstanceName field was added to the
    Pstore.  We need to iterate over all AD Pstore entries and add an
    InstanceName field with value equal to DnsDomainName.
    """
    path = "ActiveDirectory._key"
    instances = pstore_cfg.read(path)
    for instance in instances:
        # find the DnsDomainName field
        for entry in instance["_sz"]:
            if entry["_name"] == PSTORE_DNS_DOMAIN_NAME_KEY:
                instance_name = entry["value"]
                break
        # check for InstanceName, if it doesn't exist create it
        has_instance_name = False
        for entry in instance["_sz"]:
            if entry["_name"] == PSTORE_INSTANCE_NAME_KEY:
                has_instance_name = True
                break
        if not has_instance_name:
            instance["_sz"].append({"_name": PSTORE_INSTANCE_NAME_KEY,
                "value": instance_name})
    pstore_cfg.write(path, instances)

def upgrade_part1():
    """
    Upgrade Part 1: lsass Pstore upgrade
        - AD multi-instancing upgrade
    """
    if os.path.exists(AUTH_UPGRADED_PART1_FILE):
        LOGGER.info("AUTH upgrade part 1 has already occurred successfully.")
        return

    for nattempts in xrange(MAX_COMMIT_RETRIES):
        pstore_cfg = gcfg.open(gcfg.gcfg_pstore).ctx_new()
        try:
            ad_multi_instances_upgrade(pstore_cfg)

            pstore_cfg.commit()
            break
        except gcfg.RecoverableCommitError:
            LOGGER.info("Retrying pstore commit (%d).", nattempts)

    #save upgrade state
    with open(AUTH_UPGRADED_PART1_FILE, "w") as f:
        print >> f, "AUTH upgrade part 1 complete"
    os.chmod(AUTH_UPGRADED_PART1_FILE, 0640)
    LOGGER.info("AUTH upgrade part 1 complete")


def upgrade_part2():
    """
    Upgrade Part 2: lsass config updates
        - ACL policies
        - Auth provider groupnet upgrade
        - Zone groupnet upgrade
        - Zone all_auth_provider upgrade
        - cache_entry_expiry upgrade
    """
    if os.path.exists(AUTH_UPGRADED_PART2_FILE):
        LOGGER.info("AUTH upgrade part 2 has already occurred successfully.")
        return

    for nattempts in xrange(MAX_COMMIT_RETRIES):
        main_cfg = gcfg.open(gcfg.gcfg_main).ctx_new()
        try:
            acl_policies_sysctl_upgrade(main_cfg)
            auth_provider_groupnet_upgrade(main_cfg)
            zone_groupnet_upgrade(main_cfg)
            zone_all_auth_providers_upgrade(main_cfg)
            cache_entry_expiry_upgrade(main_cfg)
            krb5_cfg_to_likewise_ad_cfg(main_cfg)
            krb5_cfg_aes_upgrade(main_cfg)
            main_cfg.commit()

            # Write the krb5 changes to the /etc/krb5.conf. This needs to be done
            # after the previous krb5 changes have been saved to the main config.
            krb5Config = krb5cfg.Krb5Configuration()
            krb5Config.write_conf_file(KRB5_CFG)
            break
        except gcfg.RecoverableCommitError:
            LOGGER.info("Retrying config commit (%d).", nattempts)

    #save upgrade state
    with open(AUTH_UPGRADED_PART2_FILE, "w") as f:
        print >> f, "AUTH upgrade part 2 complete"
    os.chmod(AUTH_UPGRADED_PART2_FILE, 0640)
    LOGGER.info("AUTH upgrade part 2 complete")

def upgrade_part3():
    """
    Upgrade Part 3: Cleanup
        - ACL policies upgrade cleanup
    """
    if os.path.exists(AUTH_UPGRADED_PART3_FILE):
        LOGGER.info("AUTH upgrade part 3 has already occurred successfully.")
        return

    try:
        acl_policies_sysctl_upgrade_cleanup()

        # save upgrade state
        with open(AUTH_UPGRADED_PART3_FILE, "w") as f:
            print >> f, "AUTH upgrade part 3 complete"
        os.chmod(AUTH_UPGRADED_PART3_FILE, 0640)
        LOGGER.info("AUTH upgrade part 3 complete")
    except Exception as err:
        LOGGER.error("Failed upgrade part 3.")
        LOGGER.exception(err)

def upgrade_part4():
    """
    Upgrade Part 4: Cleanup roles
        - Role and privilege upgrade cleanup
    """
    LOGGER.info("Starting upgrade part 4: removing ISCSI priv from user defined roles")
    if os.path.exists(AUTH_UPGRADED_PART4_FILE):
        LOGGER.info("AUTH upgrade part 4 has already occurred successfully.")
        return

    try:
        db = auth.open_role_db()
        txn = db.begin_txn()
        roles = txn.roles
        for role in roles:
            if role.name not in DEFAULT_ROLES:
                for priv in role.privs:
                    if priv.name == ISI_PRIV_ISCSI:
                        role.del_privilege(priv)
            role.close()
        txn.commit()
        db.close()
    except Exception as err:
        LOGGER.error("Failed upgrade part 4.")
        return
    LOGGER.info("Upgrade part 4 complete")

    with open(AUTH_UPGRADED_PART4_FILE, "w") as f:
        print >> f, "AUTH upgrade part 4 complete"
    os.chmod(AUTH_UPGRADED_PART4_FILE, 0640)
    LOGGER.info("AUTH upgrade part 4 complete")


def main():
    try:
        lnn = "Node %d -" % iconf.getNode()['node id']
        lfmt = lnn + "%(asctime)s - %(levelname)s - %(message)s"
        LOGGER.setLevel(logging.INFO)
        fhandler = logging.FileHandler(LOG_FILE, 'a')
        fhandler.setLevel(logging.INFO)
        fhandler.setFormatter(logging.Formatter(lfmt))
        LOGGER.addHandler(fhandler)
    except EnvironmentError as err:
        syslog.syslog(syslog.LOG_NOTICE,
                      "Error running AUTH upgrade script: %s" % err)
        return 1

    try:
        os.chmod(LOG_FILE, 0640)
    except OSError as err:
        # log chmod errors and continue
        syslog.syslog(syslog.LOG_NOTICE,
                      "Error chmod'ing %s (errno: %d)" % (LOG_FILE, err.errno))

    # Block on the worker lock
    try:
        sentry = safelockfile(AUTH_UPGRADE_LOCKFILE, 'w')
    except EnvironmentError as err:
        syslog.syslog(syslog.LOG_NOTICE,
                      "Error running AUTH upgrade script: %s" % err)
        return 1

    nstat = sysver.Node_Status()
    if not nstat.upgraded_across_riptide():
        return 0

    LOGGER.info("AUTH upgrade started.")

    try:
        upgrade_part1()
        upgrade_part2()
        upgrade_part3()
        upgrade_part4()
    finally:
        sentry.close()

    return 0

if __name__ == "__main__":
    sys.exit(main())
