# Copyright (c) 2020, JINGROW
# For license information, please see license.txt


from math import ceil

import jingrow
from jingrow.utils import cint


def execute():
	pagetype = "Site Usage"
	jingrow.reload_pagetype(pagetype)
	scheme_before = jingrow.db.auto_commit_on_many_writes
	jingrow.db.auto_commit_on_many_writes = True
	records = jingrow.get_all(pagetype, pluck="name")
	total = len(records)

	for current, record in enumerate(records):
		print(f"Updated {current} of {total}", end="\r")

		fields = ["backups", "database", "public", "private"]
		current_values = jingrow.db.get_value(pagetype, record, fields)

		for field, value in zip(fields, current_values):
			value = ceil(cint(value) / (1024**2))
			jingrow.get_pg(pagetype, record).db_set(field, value, update_modified=False)

	jingrow.db.commit()
	jingrow.db.auto_commit_on_many_writes = scheme_before
	print(f"{total} {pagetype} records updated")
