#!/usr/share/ucs-test/runner python3
## -*- coding: utf-8 -*-
## desc: test load and store
## tags: [apptest]
## exposure: dangerous
## packages:
##   - univention-google-apps

import os.path
import uuid
import datetime
import shutil
import atexit
import subprocess
from six.moves.urllib.parse import quote
from six.moves.urllib.parse import urljoin

import univention.testing.strings as uts
import univention.testing.utils as utils
import univention.testing.ucr as ucr_test

from univention.googleapps.auth import GappsAuth, CREDENTIALS_FILE


ucr = ucr_test.UCSTestConfigRegistry()
ucr.load()

DATETIME_FORMAT = "%Y-%m-%d_%H:%M:%S"
CREDENTIALS_FILE_BAK = "{}.bak_{}".format(CREDENTIALS_FILE, datetime.datetime.now().strftime(DATETIME_FORMAT.replace(" ", "_")))

try:
	shutil.move(CREDENTIALS_FILE, CREDENTIALS_FILE_BAK)
	has_backup = True
except IOError:
	has_backup = False


SSL_CERT_NAME = 'gapps.test.{}@{}.{}'.format(uts.random_username(), ucr['hostname'], ucr['domainname'])
SSL_CERT_FILE = os.path.join('/etc/univention/ssl/', SSL_CERT_NAME, 'private.key')
subprocess.call('univention-certificate new -name {} -days 2'.format(SSL_CERT_NAME).split())


@atexit.register
def move_cred_file_bak():
	subprocess.call('univention-certificate revoke -name {}'.format(SSL_CERT_NAME).split())
	if has_backup:
		try:
			shutil.move(CREDENTIALS_FILE_BAK, CREDENTIALS_FILE)
		except IOError:
			pass


ga = GappsAuth(None)

project_id = uts.random_username()
domain = "{}.{}".format(uts.random_string(), uts.random_string())
email = '{}@{}'.format(project_id, domain)
key = open(SSL_CERT_FILE).read()
key_id = uuid.uuid1().hex
sub = uts.random_string()
client_id = uts.random_int(100000000000000000000, 200000000000000000000)
data = {
	'auth_provider_x509_cert_url': 'https://www.googleapis.com/oauth2/v1/certs',
	'auth_uri': 'https://accounts.google.com/o/oauth2/auth',
	'client_email': email,
	'client_id': client_id,
	'client_x509_cert_url': urljoin('https://www.googleapis.com/robot/v1/metadata/x509/', quote(email)),
	'private_key': key,
	'private_key_id': key_id,
	'project_id': project_id,
	'token_uri': 'https://accounts.google.com/o/oauth2/token',
	'type': 'service_account'
}

ga.store_credentials(data, impersonate_user=sub, domain=domain)
cred = ga.get_credentials()

if not all((
	cred._service_account_email == email,
	project_id in cred._service_account_email,
	cred._private_key_id == key_id,
	cred._private_key_pkcs8_pem == key,
	cred._kwargs["sub"] == sub,
	cred._kwargs["domain"] == domain,
	cred.client_id == client_id,
)):
	utils.fail("GappsAuth.store_credentials() -> Storage.get() didn't return what was expected.")
