#!/usr/bin/python
"""
Halfpipe Krb5 upgrade script.
Enables the weak_crypto_flag to maintain upgrade compatability with
previous versions.
"""

import sys
import logging
import time
import isi.error

import isi.gconfig as gcfg
import isi.sys.version as sysver
import isi.config.krb5 as krb5

KRB5_CONF = "/etc/krb5.conf"

MAX_COMMIT_RETRIES = 10
KRB5CFG_WEAK_CRYPTO_PATH = "krb5cfg.defaults.allow_weak_crypto"

LOGGER = logging.getLogger("halfpipe_krb5_upgrade")

def main():
    nstat = sysver.Node_Status()
    if not nstat.upgraded_across_halfpipe():
        return 0

    lfmt = "%(asctime)s - %(levelname)s - %(message)s"
    LOGGER.setLevel(logging.INFO)
    shandler = logging.StreamHandler(sys.stderr)
    shandler.setLevel(logging.INFO)
    shandler.setFormatter(logging.Formatter(lfmt))
    LOGGER.addHandler(shandler)
    LOGGER.info("Starting Halfpipe krb5 upgrade.")

    for nattempts in xrange(MAX_COMMIT_RETRIES):
        main_cfg = gcfg.open(gcfg.gcfg_main).ctx_new()
        try:
            main_cfg.write(KRB5CFG_WEAK_CRYPTO_PATH, True)
            main_cfg.commit()
            krb5.krb5_conf_write(main_cfg, KRB5_CONF)
            LOGGER.info("Halfpipe krb5 upgrade complete")
            return 0
        except (gcfg.RecoverableCommitError, isi.error.IsiError):
            LOGGER.info("Failed to commit retrying (%d).", nattempts)
            time.sleep(5 * (nattempts + 1))

    LOGGER.info("Failed to upgrade krb5 config.")
    return 1

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