#!/usr/bin/python
# Chopu SMB upgrade script

import os
import sys
import syslog
import time

from isi.app.lib import safelockfile
import isi.upgrade.smb as smbup
import isi.upgrade.preupgradechecks.smbcheck as smbcheck
import isi.sys.version as sysver

IFS_BACKUP_PATH = "/ifs/.ifsvar/tmp"
IFSVAR_SAMBA = "/ifs/.ifsvar/samba"
IFSVAR_ETC = "/ifs/.ifsvar/etc"
OLD_DEFAULT_ACL_TEMPLATE = IFSVAR_SAMBA + "/isi-share-default-acl"

# Prior to 6.5.5 the override file was /mcp/override/samba. Starting in
# 6.5.5 and above the override change to /mcp/override/smb, yet in the
# latest levels is important to check for the old filename in case the
# file was generated and later on the node was upgraded
IFSVAR_SAMBA_OVERRIDE = IFSVAR_ETC + "/mcp/override/samba"
IFSVAR_SMB_OVERRIDE = IFSVAR_ETC + "/mcp/override/smb"

LOG_FILE = os.path.join(IFS_BACKUP_PATH, "chopu-smb-upgrade.log")
SMB_UPGRADE_FILE = os.path.join(IFS_BACKUP_PATH, "chopu-smb-upgraded")

def clean_ifsvar():
    # get rid of old default ACL template
    try:
        os.unlink(OLD_DEFAULT_ACL_TEMPLATE)
    except:
        pass

    # remove /ifs/.ifsvar/samba if empty
    try:
        os.rmdir(IFSVAR_SAMBA)
    except:
        pass

def main():

    try:
        smb_upgrade = smbup.SmbUpgrade(LOG_FILE)
    except EnvironmentError, e:
        syslog.syslog(syslog.LOG_NOTICE,
                      "Error running smb upgrade script, %s"%e)
        return 0


    # We need to block all other nodes from continue until we've finished
    # the upgrade
    try:
        sentry = safelockfile(SMB_UPGRADE_FILE, 'w')
    except EnvironmentError, e:
        syslog.syslog(syslog.LOG_NOTICE,
                      "Error running smb upgrade script, %s"%e)
        return 0

    status = {}
    status['upgraded'] = smb_upgrade.run_upgrade()

    clean_ifsvar()

    # enable the smb service if it wasn't disabled
    import isi.config.mcp as mcp
    mcpconfig = mcp.mcpconfig()
    status['enabled'] = False

    # check if this an upgrade from < 6.5 . The get_previous_version()
    # call returns None if no upgrade has happened and None is evaluated
    # lower than CHOPU_VERSION.

    prev_version = sysver.Node_Status().get_previous_version()
    if prev_version is not None and prev_version < sysver.CHOPU_VERSION:
        # if a samba mcp override file exists, check its value. As we
        # are coming from a level prior to 6.5.5 look for the samba file
        if os.path.exists(IFSVAR_SAMBA_OVERRIDE):
            import xml.dom.minidom as xml
            def samba_enabled(status, c):
                assert c.nodeName == "modify-attribute", "Corrupt mcp override"
                assert c.getAttribute('id') == "samba_service"
                assert c.getAttribute('attribute') == "enable"
                status['enabled'] = bool(int(c.getAttribute('value'), 10))

            smbcheck._parse_isi_data(status,
                xml.parse(IFSVAR_SAMBA_OVERRIDE),
                'service', samba_enabled)
        # otherwise samba was never disabled and smb should be enabled
        else:
            status['enabled'] = True
    else:
        # This was not an upgrade, so the file to look for is smb. Still
        # look at the contents of the file to determine whether smb
        # should be enabled or not.
        if not os.path.exists(IFSVAR_SMB_OVERRIDE):
            status['enabled'] = True
        else:
            import xml.dom.minidom as xml
            def smb_enabled(status, c):
                assert c.nodeName == "modify-attribute", "Corrupt mcp override"
                assert c.getAttribute('id') == "smb_service"
                # Fetch the enable attribute only.
                if c.getAttribute('attribute') == "enable":
                    status['enabled'] = bool(int(c.getAttribute('value'), 10))

            smbcheck._parse_isi_data(status,
                xml.parse(IFSVAR_SMB_OVERRIDE),
                'service', smb_enabled)

    syslog.syslog(syslog.LOG_NOTICE, "chopu-smb-upgrade status: " + str(status))
    if status['upgraded'] and status['enabled']:
        syslog.syslog(syslog.LOG_NOTICE, "Enabling smb service\n")
        mcpconfig.enable('smb')

    sentry.close()

    return 0

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