# -*- coding: utf-8 -*-
# Copyright (c) 2020, JINGROW
# For license information, please see license.txt


import json

import jingrow
from jingrow.desk.pagetype.tag.tag import add_tag


def execute():
	jingrow.reload_pg("jcloud", "pagetype", "site_backup")
	bucket = jingrow.db.get_single_value("Jcloud Settings", "aws_s3_bucket")
	offsite_backups = [
		jingrow.get_pg("Site Backup", x["name"])
		for x in jingrow.get_all("Site Backup", {"offsite": 1})
	]

	for offsite_backup in offsite_backups:
		offsite_job_payload = json.loads(offsite_backup.offsite_backup or "{}")
		if offsite_job_payload:
			remote_database = offsite_job_payload.get(offsite_backup.get("database_file"))
			remote_public = offsite_job_payload.get(offsite_backup.get("public_file"))
			remote_private = offsite_job_payload.get(offsite_backup.get("private_file"))

			if remote_database:
				remote_file = jingrow.get_pg(
					{
						"pagetype": "Remote File",
						"file_name": offsite_backup.database_file,
						"file_path": remote_database,
						"file_size": offsite_backup.database_size,
						"file_type": "application/x-gzip",
						"bucket": bucket,
					}
				)
				remote_file.save()
				add_tag("Offsite Backup", remote_file.pagetype, remote_file.name)
				offsite_backup.remote_database_file = remote_file.name

			if remote_public:
				remote_file = jingrow.get_pg(
					{
						"pagetype": "Remote File",
						"file_name": offsite_backup.public_file,
						"file_path": remote_public,
						"file_size": offsite_backup.public_size,
						"file_type": "application/x-tar",
						"bucket": bucket,
					}
				)
				remote_file.save()
				add_tag("Offsite Backup", remote_file.pagetype, remote_file.name)
				offsite_backup.remote_public_file = remote_file.name

			if remote_private:
				remote_file = jingrow.get_pg(
					{
						"pagetype": "Remote File",
						"file_name": offsite_backup.private_file,
						"file_path": remote_private,
						"file_size": offsite_backup.private_size,
						"file_type": "application/x-tar",
						"bucket": bucket,
					}
				)
				remote_file.save()
				add_tag("Offsite Backup", remote_file.pagetype, remote_file.name)
				offsite_backup.remote_private_file = remote_file.name

			offsite_backup.save()

	jingrow.db.commit()
