#!/usr/bin/env python
#
# Expire old snapshots

import zfs, commands, datetime, os

# List of filesystems to expire
# XXX MCL
expirelist=(("a", 14), 
            ("a/nfs", 14),
            ("a/local", 14),
            ("a/portbuild", 14),
            ("a/portbuild/amd64", 14),
            ("a/portbuild/i386", 14),
            ("a/portbuild/ia64", 14),
            ("a/portbuild/powerpc", 14),
            ("a/portbuild/sparc64", 14),
            ("a/snap", 7),
            ("a/snap/ports", 7),
            ("a/snap/src-6/src", 7),
            ("a/snap/src-7/src", 7),
            ("a/snap/src-8/src", 7),
            ("a/snap/src-9/src", 7),
            ("a/snap/world-amd64-HEAD", 7),
            ("a/snap/world-i386-HEAD", 7))

now = datetime.datetime.now()
print "zexpire: starting at " + now.ctime()

for (fs, maxage) in expirelist:
    print

    try:
        snapdata = zfs.getallsnaps(fs)
    except zfs.NoSuchFS:
        print "no such fs %s, skipping" % fs
        continue

    snaps = (i[0] for i in snapdata)

    for snap in snaps:
        try:
            snapdate = datetime.datetime.strptime(snap, "%Y%m%d%H%M")
        except ValueError:
            try:
                snapdate = datetime.datetime.strptime(snap, "%Y%m%d%H%M%S")
            except ValueError:
                print "zexpire: don't know what to do with snap `" + snap + "'"
                continue

        if (now - snapdate) > datetime.timedelta(days=maxage):
            print "Snapshot %s@%s too old, attempting zfs destroy" % (fs, snap)
            (err, out) = commands.getstatusoutput("zfs destroy %s@%s" % (fs,snap))

            if err:
                print "Error deleting snapshot", out

then = datetime.datetime.now()
print
print "zexpire: ending at " + then.ctime()
