#!/usr/bin/env python3
# rm_uncommented_snaps Copyright (c) 2009 James Loh 
# 1 Jan 2022 Modified for Python 3
#
#   Permission is hereby granted, free of charge, to any person
#   obtaining a copy of this software and associated documentation files
#   (the "Software"), to deal in the Software without restriction,
#   including without limitation the rights to use, copy, modify, merge,
#   publish, distribute, sublicense, and/or sell copies of the Software,
#   and to permit persons to whom the Software is furnished to do so,
#   subject to the following conditions:
#
#   The above copyright notice and this permission notice shall be
#   included in all copies or substantial portions of the Software.
#
#   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 
#   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
#   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
#   IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 
#   CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, 
#   TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 
#   SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 

from datetime import datetime, date
import subprocess
import re

DAYS_TO_KEEP = 7 

comment_pattern = re.compile(r".*@\S{21}-(?P<comment>.*)")

def remove_snapshot(snapshot_name):
    snapshot_destroy_cmd =  "zfs destroy -r " + snapshot_name
    print(snapshot_destroy_cmd)
    cp = subprocess.run([snapshot_destroy_cmd], shell=True, universal_newlines=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    print(cp.stdout)
    print(cp.stderr)

def main():
    snapshot_list_cmd = "zfs list -t snapshot -H| awk '{print $1;}'"
    cp = subprocess.run([snapshot_list_cmd], shell=True, universal_newlines=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    print(cp.stderr)

    today = datetime.now().date()
    for snapshot_name in cp.stdout.split('\n'):
        commented = comment_pattern.search(snapshot_name)
        if (commented):
            continue
    
        i = snapshot_name.find('@')
        if i < 0:
            continue
    
        year = int(snapshot_name[i+1:i+5])
        month = int(snapshot_name[i+5:i+7])
        day = int(snapshot_name[i+7:i+9])
        prev_day = date(year, month, day)
        delta = today - prev_day
    
        if delta.days > DAYS_TO_KEEP:
            remove_snapshot(snapshot_name)

if __name__ == "__main__":
    main()
