#!/usr/bin/python

import os
import logging
import isi.misc as misc
import sys
import traceback

import isi.fs.lib as fslib
import isi.sys.version as sysver


LOGFILE = "/var/log/isi_snapshot_d.log"
PRE_DSBT_ORPHANED_SNAPS_DONE = \
        "/ifs/.ifsvar/modules/isi_snapshots/.pre_dsbt_snaps_done"
PROG = os.path.basename(sys.argv[0])

def create_done_file():
    fd = os.open(PRE_DSBT_ORPHANED_SNAPS_DONE, \
            os.O_RDONLY | os.O_CREAT | os.O_EXLOCK, 0444)
    os.close(fd)
    logging.info("%s: Created %s" %
            (PROG, PRE_DSBT_ORPHANED_SNAPS_DONE))

def main():
    """
    Create the file only if we are not upgrading across waikiki.
    """
    try:
        logging.basicConfig(filename=LOGFILE, level=logging.INFO,)
        nstat = sysver.Node_Status()
        need_upgrade = nstat.upgraded_across_waikiki()
        if os.path.exists(PRE_DSBT_ORPHANED_SNAPS_DONE):
            logging.debug("%s: %s already exists" %
                    (PROG, PRE_DSBT_ORPHANED_SNAPS_DONE))
        elif need_upgrade:
            logging.info("%s: Upgrading snapshots for waikiki" %
                    PROG)
        else:
            create_done_file()

    except Exception, e:
        dexitcodes = fslib.getProcDexitcodes()
        logging.exception("%s: Failed to run %s with %s: [%s]"
                % (misc.hostname(), PROG, traceback.print_exc(e), dexitcodes))
        sys.exit(1)

    finally:
        sys.exit(0)

if __name__ == '__main__':
    main()
