#!/usr/bin/env python3

from json import load, dump
from subprocess import check_output
from shutil import move
from os import remove
from collections import defaultdict

with open('/etc/backup-server/config.json', 'r') as f:
    server_settings = load(f)

snapshots = defaultdict(set)

for line in check_output('LC_ALL=C zfs list -H -t snapshot -o name', shell=True).splitlines():
    line = line.decode('UTF-8')

    if line.startswith('{}/'.format(server_settings['zfs-base'])):
        dataset, snapname = line.split('@', 1)

        dataset = dataset.split('/')[-1]
        ts, bucket = snapname.split('-', 1)

        if not ts.isdigit():
            # garbage, ignore
            continue

        snapshots[dataset].add(int(ts))

backups = {}
for dataset, snaps in snapshots.items():
    backups[dataset] = sorted(snaps)[-1]

with open('/etc/backup-server/backups.tmp.json', 'w') as f:
    dump(backups, f)

move(
    '/etc/backup-server/backups.tmp.json',
    '/etc/backup-server/backups.json',
)