#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Extract UCS overview translations.
"""
#
# Copyright 2016-2021 Univention GmbH
#
# https://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
# <https://www.gnu.org/licenses/>.

import argparse
import polib
import re
import subprocess
import sys
try:
	from typing import List, Tuple  # noqa F401
except ImportError:
	pass

UCR_ASSIGNMENT = re.compile(r'(ucs/web/overview/entries.*(?:link|description|label))[=?](.*)')
# directory names to ignore
DIR_BLACKLIST = set(['.git', '.svn', 'doc', 'test'])


def write_po_file(ucrv_assingments, file_name):
	# type: (List[Tuple[str, str]], str) -> None
	pof = polib.POFile(check_for_duplicates=True)
	for ucrv, value in ucrv_assingments:
		po_ent = polib.POEntry(occurrences=[(ucrv, None)], msgid=value)
		try:
			pof.append(po_ent)
		except ValueError:
			dupe = pof.find(po_ent.msgid)
			if ucrv in [dupe_ucrv for dupe_ucrv, _ in dupe.occurrences]:
				continue
			else:
				dupe.occurrences.append((ucrv, None))
	pof.save(file_name)


def parse_args():
	# type: () -> argparse.Namespace
	parser = argparse.ArgumentParser(description=__doc__)
	parser.add_argument(
		'--source', '-s',
		help="UCS source code checkout to search for overview page translations",
		required=True)
	parser.add_argument(
		'--language_code', '-l',
		help="two char language code, e.g. 'fr'",
		required=True)
	args = parser.parse_args()
	return args


def main():
	# type: () -> None
	args = parse_args()

	cmd = [
		'grep',
		'--recursive',
		'--no-filename',
		r'overview/.*\(link\|description\|label\)[=?]',
		args.source]
	cmd.extend(['--exclude-dir={}'.format(dname) for dname in DIR_BLACKLIST])

	try:
		out = subprocess.Popen(cmd, stdout=subprocess.PIPE)
	except EnvironmentError as exc:
		exit('Failed to execute grep: %s' % (exc,))

	assert out.stdout
	ucrv_assingments = []  # type: List[Tuple[str, str]]
	for line in out.stdout:
		line = line.strip()
		if not line:
			continue
		line = line.replace('ucr set ', '').replace('"', '').replace('\'', '')
		line = line.strip(' \\')
		matches = UCR_ASSIGNMENT.match(line)
		if not matches:
			sys.exit('Error: Received unexpected input from grep:\n{}\n'.format(line))

		ucrv_assingments.append(matches.groups())  # type: ignore

	write_po_file(ucrv_assingments, 'ucr-l10n.po')


if __name__ == '__main__':
	main()
