# -*- coding: utf-8 -*-

"""
Backup plan for Odoo databases
::::::::::::::::::::::::::::::

Keep :

- all saves the last week
- one save per week the last month
- one save per month the last year
"""

from datetime import datetime
from os import unlink
from glob import glob

DT = datetime.now()

def notkeep(fname):
    """ Filter all obsolete save files """
    fname = fname.split('/')[-1]
    fname = fname.split('_')
    if len(fname) <= 1:
        return False
    save_date = fname[0]
    save_date = datetime.strptime(save_date, '%Y-%m-%d')
    delta = DT - save_date
    if delta.days > 365:
        return True
    elif delta.days > 31:
        if save_date.day != 1:
            return True
    elif delta.days > 7:
        if (save_date.weekday() != 0) and (save_date.day != 1):
            return True
    else:
        return False

# Filters zip files and keeps only legitimate ones
# ================================================

FILES = glob('backups/*.zip')
BACKUPS_TO_REMOVE = filter(notkeep, FILES)

if len(BACKUPS_TO_REMOVE) > 0:
    print('Save files outdated, will be deleted : \n\n* ' +
          '\n* '.join(BACKUPS_TO_REMOVE))

for b in BACKUPS_TO_REMOVE:
    unlink(b)
