#!/usr/bin/python

import logging
import os
import sys
import syslog

import isi.fs.collect as collect
import isi.misc as misc
import isi.sys.version as version

IFS_SAVE_PATH = "/ifs/.ifsvar/upgrade_scripts_done"
BUG_103358_DIR = os.path.join(IFS_SAVE_PATH, "mavericks-bug-103358")
BUG_103358_FILE = os.path.join(BUG_103358_DIR, "mavericks-bug-103358")
LOG_FILE = os.path.join(BUG_103358_DIR, "mavericks-bug-103358.log")

#
# The problem was that a collect started pre-7.0 uses 1::INVALID_SNAPID as the
# owner when marking LIN blocks while 7.0 uses 1::HEAD_SNAPID. So, we cancel
# any running marks. Also, if the block history was set to ALLOCS mode we
# don't reset the block history block at all and even a new mark started on
# 7.0 would show block history violations with changed owner snapid.
#
# This is safe to be run multiple times on the first upgrade. Though, this
# shouldn't be run at all after the first upgrade from 6.5*.
#
def main():
    try:
        # Doesn't hurt creating a directory once even without upgrade
        os.makedirs(BUG_103358_DIR)
    except OSError, e:
        # Only ignore if it exists
        if not os.path.isdir(BUG_103358_DIR):
            syslog.syslog(syslog.LOG_NOTICE, "Failed to create %s" \
                    % BUG_103358_DIR)
            return 1
        else:
            pass

    try:
        logging.basicConfig(filename=LOG_FILE, level=logging.INFO,)
    except EnvironmentError, e:
        syslog.syslog(syslog.LOG_NOTICE, "Error running %s: %s" \
                % (sys.argv[0], e))
        return 1

    try:
        # Run only on an upgrade across Mavericks
        version_status = version.Node_Status()
        if not version_status.upgraded_across_mavericks():
            logging.debug("%s: Upgrade not needed" % misc.hostname())
            return 0

        # Don't run multiple times
        if os.path.exists(BUG_103358_FILE):
            logging.debug("%s: Already upgraded" % misc.hostname())
            return 0

        collect.cancelCollect()
        #
        # All we want to do is increment the block history cookie but we can't
        # do that without setting the status. Just set it twice to make sure it
        # was updated in case it was changed on the cluster.
        # Keep it marks on release builds and allocs on debug.
        #
        if misc.osflavor() == 0:
            # Release
            misc.ifs_test_thread("block_history_status(allocs)")
            misc.ifs_test_thread("block_history_status(marks)")
        elif misc.osflavor() == 1:
            # Debug
            misc.ifs_test_thread("block_history_status(marks)")
            misc.ifs_test_thread("block_history_status(allocs)")
    except Exception, e:
        logging.exception("%s: Failed to run %s with %s" \
                % (misc.hostname(), sys.argv[0], e))
        return 1

    try:
        f = open(BUG_103358_FILE, 'w')
        msg = "Canceled Collect and updated block history on 7.0 upgrade " \
              "from %s" % misc.hostname()
        f.write(msg)
        f.close()
        logging.info(msg)
    except:
        logging.exception("%s: Failed to write to %s" \
                % (misc.hostname(), BUG_103358_FILE))
        return 1

    logging.shutdown()

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