#! /usr/bin/python3

# Univention Google Workspace App - handle auth
#
# Copyright 2018-2019 Univention GmbH
#
# http://www.univention.de/
#
# All rights reserved.
#
# The source code of this program is made available
# under the terms of the GNU Affero General Public License version 3
# (GNU AGPL V3) as published by the Free Software Foundation.
#
# Binary versions of this program provided by Univention to you as
# well as other copyrighted, protected or trademarked materials like
# Logos, graphics, fonts, specific documentations and configurations,
# cryptographic keys etc. are subject to a license agreement between
# you and Univention and not subject to the GNU AGPL V3.
#
# In the case you use this program under the terms of the GNU AGPL V3,
# the program is provided in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public
# License with the Debian GNU/Linux or Univention distribution in file
# /usr/share/common-licenses/AGPL-3; if not, see
# <http://www.gnu.org/licenses/>.

# Parse univention Google Workspace credentials.json file and convert
# it to the new format required by the updated oauth2client version

from univention.googleapps.auth import CREDENTIALS_FILE

from shutil import copy2
import json
import base64
import sys
import datetime


DATETIME_FORMAT = "%Y-%m-%d_%H:%M:%S"


try:
	print("Converting gsuite credentials file to new format")
	with open(CREDENTIALS_FILE, "r") as json_data:
		j = json.load(json_data)

	if j["_class"] == "ServiceAccountCredentials":
		print("INFO: File seems to be already converted, exiting")
		sys.exit(0)

	if j["_class"] != "SignedJwtAssertionCredentials":
		print("ERROR: excepted _class does not match 'SignedJwtAssertionCredentials'")
		sys.exit(1)

	print("  Converting format")
	# Start conversion
	# Unmodified fields: access_key, assertion_type, client_secret, id_token, invalid
	# refresh_token, revoke_uri, token_expiry, token_response, token_uri, user_agent
	j["_class"] = "ServiceAccountCredentials"
	j["_module"] = "oauth2client.service_account"
	j["_kwargs"] = j.pop("kwargs")
	j["_private_key_pkcs8_pem"] = base64.b64decode(j.pop("private_key"))
	j["_scopes"] = j.pop("scope")
	j["_service_account_email"] = j.pop("service_account_name")
	j["_user_agent"] = j.pop("user_agent")
	j["client_id"] = j["_kwargs"].pop("client_id")  # client_id moved from kwargs to top level
	j["scopes"] = []  # new empty array scopes
	j["token_info_uri"] = None  # new empty value

	# removed fields
	j.pop("private_key_password")

	# Required field for parsing, optional key in new oauth2client version
	j["_private_key_id"] = None

	print("  Creating file backup")
	# Create backup
	copy2(CREDENTIALS_FILE, "%s.%s.bak" % (CREDENTIALS_FILE, datetime.datetime.now().strftime(DATETIME_FORMAT.replace(" ", "_"))))

	print("  Write converted file")
	with open(CREDENTIALS_FILE, "wb") as modified_file:
		json.dump(j, modified_file)

except IOError as e:
	print("IOError: %s" % e)
	sys.exit(2)
