# Copyright (c) 2023, JINGROW
# For license information, please see license.txt
import jingrow
from tqdm import tqdm


def execute():
	jingrow.reload_pg("jcloud", "pagetype", "site")
	sites = jingrow.get_all(
		"Site",
		{
			"status": ("!=", "Archived"),
			"is_database_access_enabled": True,
			"database_access_user": ("is", "not set"),
		},
		ignore_ifnull=True,
	)
	for site in tqdm(sites):
		try:
			site = jingrow.get_pg("Site", site.name)
			config = site.fetch_info()["config"]
			site.database_access_user = config["db_name"]
			site.database_access_password = config["db_password"]
			site.database_access_mode = "read_write"
			site.save()
			jingrow.db.commit()
		except Exception as e:
			jingrow.db.rollback()
			print(f"Couldn't set DB credentials for site {site.name}: {e}")
