import os
import sys
import tempfile
import shutil
from pprint import pprint, pformat
from ipalib import api
from ipalib.config import Env
from ipalib.constants import DEFAULT_CONFIG
from ipalib.install.kinit import kinit_password
from ipapython.ipautil import run
from ipaplatform.paths import paths


principal = "admin"
password = "SomeADMINpassword"


def temp_kinit(principal, password):
    if not password:
        print("password is needed")
        sys.exit(1)
    if not principal:
        principal = "admin"

    ccache_dir = tempfile.mkdtemp(prefix='krbcc')
    ccache_name = os.path.join(ccache_dir, 'ccache')

    try:
        kinit_password(principal, password, ccache_name)
    except RuntimeError as e:
        print("Kerberos authentication failed: {}".format(e))
        sys.exit(2)

    return ccache_dir, ccache_name


def temp_kdestroy(ccache_dir, ccache_name):
    if ccache_dir is not None:
        shutil.rmtree(ccache_dir, ignore_errors=True)
    if ccache_name is not None:
        run([paths.KDESTROY, '-c', ccache_name], raiseonerr=False)


def api_connect():
    env = Env()
    env._bootstrap()
    env._finalize_core(**dict(DEFAULT_CONFIG))

    api.bootstrap(context='server', debug=env.debug, log=None)
    api.finalize()
    api.Backend.ldap2.connect()


ccache_dir = None
ccache_name = None
try:
    ccache_dir, ccache_name = temp_kinit(principal, password)
    api_connect()

    host_name = "batch-test-host-01"
    domain = api.env.domain
    host_fqdn = "%s.%s" % (host_name, domain)

    print("Init\n")

    try:
        api.Command["host_del"](host_fqdn, **{'updatedns': True})
    except Exception as e:
        pass
    
    print("Add host %s\n" % host_fqdn)

    api.Command["host_add"](host_fqdn, **{'force': True})

    batch_args = [
        {
            "method": "host_mod",
            "params": ([host_fqdn],
                       {
                           "updatedns": True,
                       })
        },
        {
            "method": "host_mod",
            "params": ([host_fqdn],
                       {
                           "location": "bar",
                       })
        },
    ]
    
    print("Run batch:\n%s\n" % pformat(batch_args))

    try:
        ret = api.Command["batch"](batch_args)
    except Exception as e:
        print(repr(e))

    try:
        pprint(repr(ret))
    except Exception as e:
        print(str(e))

    print("\nlocation: %s\n" % repr(api.Command["host_show"](host_fqdn)["result"].get("nshostlocation")))

except Exception as e:
    print(repr(e))

finally:
    temp_kdestroy(ccache_dir, ccache_name)
