#!/usr/bin/env python3




import os
import datetime
from pathlib import Path
import sys
import subprocess
import shutil
from typing import Optional
import healthchecks

# detect if we are sunday (full backup) or another day (diff)

stanza_name = sys.argv[1]
server_name = sys.argv[2]
slug = f"pgbackrest-{server_name}"


last_fullbackup_file = Path(f"~/.state/pgbackrest-runs/last-fullbackup-{stanza_name}").expanduser()

last_fullbackup: Optional[datetime.datetime] = None

if last_fullbackup_file.exists():
    try:
        datetimeStr = last_fullbackup_file.read_text()
        last_fullbackup = datetime.datetime.strptime(datetimeStr, '%Y-%m-%d %H:%M:%S.%f')
    except:
        last_fullbackup = None
else:
    last_fullbackup = None


if last_fullbackup:
    days = (datetime.datetime.now() - last_fullbackup).days
    print(f"days since last full backup is {days} days ago")
    if days > 6.5:
        backup_type = "full"
    else:
        backup_type = "diff"
else:
    backup_type = "full"

print(f"last full backup is {last_fullbackup}")
print(f"backup type {backup_type}")

command = [
    "runitor",
    "-ping-key=" + healthchecks.ping_key,
    f"-slug={slug}",
    "--",
    "pgbackrest",
    f"--type={backup_type}",
    f"--stanza={stanza_name}",
    "backup",
    "--repo=1",
]

commandStr = " ".join(command)
print(f"running -- {commandStr}")

subprocess.run(command)

# 30 22  *   *   0     /usr/bin/runitor -ping-key=XYZPDQ-AAAAAAAAAAA -slug=getty-db-backup -- pgbackrest --type=full --stanza=getty backup --repo=1
# 30 22  *   *   1-6   /usr/bin/runitor -ping-key=XYZPDQ-AAAAAAAAAAA -slug=getty-db-backup -- pgbackrest --type=diff --stanza=getty backup --repo=1


if backup_type == "full":
    last_fullbackup_file.parent.mkdir(parents=True, exist_ok=True)
    last_fullbackup_file.write_text(str(datetime.datetime.now()))

