#!/opt/cycle/jetpack/system/python/bin/python3

import logging
import logging.handlers
import os
import sys

import jetpack
import jetpack.util

LOG_FILE = os.path.join(jetpack.util.jetpack_home(), "logs", "initialize.log")

# Set up logging that can appropriately detach from the main process with the daemon
logger = logging.getLogger()
logger.setLevel(logging.INFO)
logger.propagate = False
fh = jetpack.util.DirOwnedRotatingFileHandler(LOG_FILE, maxBytes=1024 * 1024 * 50, backupCount=5)
fh.setLevel(logging.INFO)
fh.setFormatter(logging.Formatter('%(asctime)s %(levelname)-8s %(message)s'))
logger.addHandler(fh)

if __name__ == "__main__":
    # This is a no-op if we've already converged once since it will have already been run to completion
    if jetpack.util.has_converged():
        sys.exit(0)

    try:
        jetpack.initialize()
    except jetpack.util.UserError as e:
        jetpack.util.write_configuration_exception(e)
        raise Exception(str(e))
    except Exception as e:
        jetpack.util.write_configuration_exception(e)
        logger.exception("Failure initializing jetpack")
        sys.exit(1)