#!/usr/bin/env python3
#
# Perform tasks on the first run of the system.

# Each task must be written in a way that prevents any damage upon repeated
# calls.
# - Cleanup tasks should ensure that the expected old data is present or
#   otherwise ensure that no second cleanup is done.
# - Setting variables should check that the previous value is the expected
#   original default and skip initialization in that case.

import os
import importlib.machinery
import sys
import logging
import pprint

try:
    from . import first_run
except ImportError:
    import first_run

# Calculate the module path from the current path
base_path = os.path.realpath(os.path.join(os.path.dirname(__file__), '..'))
config_path = os.path.join(base_path, 'config')

# Load configuration
config = importlib.machinery.SourceFileLoader(
    'config', os.path.join(config_path, 'first_run_conf.py')).load_module()


def do_first_run():
    first_run.run_commands(config.pre_cmds)

    output = []
    # database
    statements = first_run.make_set_db_statements(config.set_db)
    output.append(
        first_run.send_db_statements(config.dbconn_string, statements)
    )

    # zope / web
    output.append(first_run.url_calls(
        commands=config.send_requests,
        redirects=True,
        resultparsefunc=first_run.perfact_result_parser
    ))

    first_run.run_commands(config.post_cmds)
    return output


if __name__ == '__main__':
    if not os.getuid() == 0:
        print("This script needs to be run as 'root'")
        sys.exit(1)

    if not os.path.isfile(config.signal_filename):
        # This is the normal case after each boot. No error.
        print("Signal file not found. Exiting.")
        print(
            "Hint: To enable 'rollout-first-run' you need to 'touch':"
            f" {config.signal_filename}"
        )
        sys.exit(0)

    # Immediately remove the file to block subsequent runs.
    os.unlink(config.signal_filename)

    if os.path.isfile(config.log_filename):
        # Someone set the signal, but the log blocks us. Error.
        print("Log file already exists. Exiting.")
        print(
            "Hint: To enable 'rollout-first-run' you need to delete the"
            f" log file at: {config.log_filename}"
        )
        sys.exit(0)

    # Block any simultaneous run by writing to the log file immediately.
    logging.basicConfig(
        format='%(asctime)s %(levelname)-8s %(message)s',
        level=logging.INFO,
        datefmt='%Y-%m-%d %H:%M:%S',
        filename=config.log_filename,
    )
    logging.info("Rollout First Run starting.")

    out = do_first_run()
    pretty = pprint.pformat(out)
    logging.info("""Output of commands:
%s""" % pretty)

    logging.info("Rollout First Run completed successfully.")
    sys.exit(0)
