#!/usr/bin/env python3
import sys
import os
import re

def collect_whitelist(file_path: str) -> 'list[str]':
	"""
	Collect programs in whitelist:
	```yaml
	NAME:
	  VERSION:
	    # ...
	    whitelist:
	      # ...
	      _default: '["/path/to/prog1","/path/to/prog2"]'
	      # ...
	    # ...
	```
	"""
	if not os.path.exists(file_path):
		print(f"failed to read dbus config: file '{file_path} not exists'")
		sys.exit(1)
	with open(file_path, "r", encoding="utf-8") as file:
		found_whitelist = False
		lines = [line.rstrip('\n') for line in file]
		for line in lines:
			if line.endswith("whitelist:"):
				found_whitelist = True
				continue
			if found_whitelist and line.lstrip().startswith("_default:"):
				raw_data = line.lstrip().split(":", 1)[1].strip("[] '\n\"")
				progs = re.split(r'" *, *"', raw_data)
				if len(progs) < 2:
					# Regex not matched
					print(f"failed to collect whitelist: no valid path format found in dbus config file {file_path}")
					return []
				return progs
		print(f"failed to collect whitelist: whitelist not found in dbus config file {file_path}")
		return []

def merge_whitelist(from_file_path: str, to_file_path: str):
	"""
	Read whitelist in `from_file_path` and save in file `to_file_path`
	"""
	from_progs = collect_whitelist(from_file_path)
	to_progs = collect_whitelist(to_file_path)
	merged_progs = list(dict.fromkeys(from_progs + to_progs))
	final_contents: list[str] = []
	with open(from_file_path, "r", encoding="utf-8") as file:
		found_whitelist = 0
		lines = [line.rstrip('\n') for line in file]
		for line in lines:
			if line.endswith("whitelist:"):
				final_contents.append(line)
				found_whitelist += 1
				continue
			if found_whitelist == 1 and line.lstrip().startswith("_default:"):
				# Here is the whitelist line.
				split_idx = line.index(":")
				progs_content = '","'.join(merged_progs)
				# line: "      _default: '["/path/prog1","/path/prog2""]'
				line_content = f"{line[0:split_idx]}: '[\"{progs_content}\"]'"
				final_contents.append(line_content)
				found_whitelist += 1
				continue

			final_contents.append(line)
	with open(to_file_path, "w", encoding="utf-8") as file:
		file.write("\n".join(final_contents))
		file.write("\n")

if __name__ == "__main__":
	if len(sys.argv) < 3 :
		print("usage: <from-file> <to-file>")
		sys.exit(1)
	merge_whitelist(sys.argv[1], sys.argv[2])
