#!/usr/bin/env python3


import os
import datetime
from pathlib import Path
import sys
import subprocess
import shutil
import healthchecks
import rotation


def logit(msg: str) -> None:
    print(msg)
    sys.stdout.flush()


rsnapshot_config_file = Path(sys.argv[1])
stanza = sys.argv[2]

neededRotations = rotation.load_needed_rsnapshot_rotations(stanza)

rotationNames = neededRotations.map(lambda r: r.rotationName).mk_str(" ")
logit(f"rotationNames -- {rotationNames}")

if neededRotations.is_empty():
    logit("no rotations needed")

else:

    def run_rsnapshot(action: str) -> None:
        command = [
            "rsnapshot",
            "-c",
            rsnapshot_config_file,
            action,
        ]

        logit(f"running -- {command}")

        retcode = subprocess.call(command, cwd = rsnapshot_config_file.parent)

        if retcode != 0:
            logit(f"command failed {retcode}")
            sys.exit(retcode)

    run_rsnapshot("sync")

    for r in neededRotations:
        run_rsnapshot(r.rotationName)
        r.rotationCompletedSuccessfully()


