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

import base64
import datetime
import shutil
import atexit

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

from univention.googleapps.auth import GappsAuth, CREDENTAILS_FILE, SSL_KEY_FILE

LOG_DATETIME_FORMAT = "%Y-%m-%d_%H:%M:%S"
CREDENTAILS_FILE_BAK = "{}.bak_{}".format(CREDENTAILS_FILE, datetime.datetime.now().strftime(LOG_DATETIME_FORMAT.replace(" ", "_")))
SSL_KEY_FILE_BAK = "{}.bak_{}".format(SSL_KEY_FILE, datetime.datetime.now().strftime(LOG_DATETIME_FORMAT.replace(" ", "_")))

try:
	shutil.move(CREDENTAILS_FILE, CREDENTAILS_FILE_BAK)
	has_backup = True
except IOError:
	has_backup = False

try:
	shutil.move(SSL_KEY_FILE, SSL_KEY_FILE_BAK)
	has_backup = True
except IOError:
	has_backup = has_backup or False


@atexit.register
def move_cred_file_bak():
	if has_backup:
		try:
			shutil.move(CREDENTAILS_FILE_BAK, CREDENTAILS_FILE)
		except IOError:
			pass
		try:
			shutil.move(SSL_KEY_FILE_BAK, SSL_KEY_FILE)
		except IOError:
			pass


ga = GappsAuth(None)

email = uts.random_string()
key = uts.random_string()
scope = uts.random_string()
sub = uts.random_string()
ga.store_ssl_key(key)
ga.store_credentials(client_email=email, scope=scope, impersonate_user=sub)
cred = ga.get_credentials()

if not (
	cred.service_account_name == email and
	cred.private_key == base64.b64encode(key) and
	cred.scope == scope and
	cred.kwargs["sub"] == sub):
		utils.fail("GappsAuth.store_credentials() -> Storage.get() didn't return what was expected.")
