#! /usr/bin/python3

import sys
import os
import re
from subprocess import run
import argparse
from glob import glob
from datetime import datetime, timedelta

if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        description='Enregistre la base de données')
    parser.add_argument(
        '--verify', action='store_true',
        help="(Optionnel) vérifier ce qui serait fait, sans rien faire vraiment")
    parser.add_argument(
        'dbdir', help="Répertoire contenant la base de données")
    options = parser.parse_args(sys.argv[1:])
    cmd = f"cd {options.dbdir}; " + \
        "zip media/sauvegarde/db-$(date +%Y-%m-%d_T_%H-%M-%S).sqlite3.zip " + \
        "db.sqlite3 > /dev/null 2>&1"
    if options.verify:
        print("On lancerait la commande :", repr(cmd))
    else:
        run(cmd, shell=True)
    saved = glob(os.path.join(options.dbdir, "media", "sauvegarde", "db*.zip"))
    save_dic={}
    for s in saved:
        m = re.match(
            r".*/db.*(\d\d\d\d)-(\d\d)-(\d\d)[_T]*(\d\d)-(\d\d)-(\d\d).*\.zip",
            s)
        if m:
            save_dic[s] = datetime(
                year = int(m.group(1)),
                month = int(m.group(2)),
                day = int(m.group(3)),
                hour = int(m.group(4)),
                minute = int(m.group(5)),
                second = int(m.group(6)),
            )
    plusDeQuinzeJours = datetime.now() - timedelta(days=14)
    plusDeQuatremois = datetime.now() - timedelta(days=4*30.5)
    for s in save_dic:
        wd = save_dic[s].date().weekday()
        vieux = save_dic[s] < plusDeQuinzeJours
        tresvieux = save_dic[s] < plusDeQuatremois
        if vieux and wd != 6 or tresvieux:
            day = (
                "lundi,mardi,mercredi,jeudi,vendredi,samedi,dimanche").split(
                    ",")[wd]
            if tresvieux:
                explication = "fichier de plus de 4 mois"
            else:
                explication = f"fichier de plus de 15 jours, {day} (pas un dimanche)"
            if options.verify:
                print("On effacerait", s, explication)
            else:
                os.unlink(s)
