#!/usr/bin/python3
# coding=utf8
#
# The MIT License (MIT)
#
# Copyright (c) 2015 Lorenz Hüdepohl
#
# 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.

import sys
import time
import argparse
import locale
from subprocess import Popen, PIPE, check_call
from shutil import which

parser = argparse.ArgumentParser(
            formatter_class=argparse.RawTextHelpFormatter,
            description='''
 Use with cron to make periodic ZFS snapshots, with the option of keeping
 only a limited number of old snapshots.

 For every ZFS filesystem that has the user property 'autosnapshot:TAGNAME'
 a snapshot is created. The value must be a positive number or the string
 "keep-all", which is used as the number of old snapshots to keep. If there
 are more, the oldest are destroyed.

 Additionally, a number of minutes can be appended with a comma, a new
 snapshot is then only created if the newest existing snapshot is older
 than this duration

 If the value is "none" the filesystem is ignored (useful to prohibit property
 inheritance).


 Example usage for systems that are typically running (e.g. servers):

   Setup properties:

    #> zfs set autosnapshot:5min=12         dpool/fs
    #> zfs set autosnapshot:hourly=24       dpool/fs
    #> zfs set autosnapshot:daily=7         dpool/fs
    #> zfs set autosnapshot:weekly=keep-all dpool/fs

   Use with this crontab:

    @weekly     zfs_auto_snapshot weekly
    @daily      zfs_auto_snapshot daily
    @hourly     zfs_auto_snapshot hourly
    */5 * * * * zfs_auto_snapshot 5min

 Example usage for systems that are only running some of the time (e.g. laptops):

   Properties:

    #> zfs set autosnapshot:5min=12,5             dpool/fs
    #> zfs set autosnapshot:hourly=24,60          dpool/fs
    #> zfs set autosnapshot:daily=7,1440          dpool/fs
    #> zfs set autosnapshot:weekly=keep-all,10080 dpool/fs

   Use e.g. with this crontab (to check every few minutes whether to update
   any of the snapshots)

    */5  * * * * zfs_auto_snapshot 5min
    */15 * * * * zfs_auto_snapshot hourly
    */30 * * * * zfs_auto_snapshot daily
    */30 * * * * zfs_auto_snapshot weekly
''')

parser.add_argument('tagname', metavar='TAGNAME', type=str,
                help='Consider all filesystems with an \'autosnapshot:TAGNAME\'\nproperty.\n'
                     'If TAGNAME is of the form TAG=VALUE, the value of the ZFS\n'
                     'property will be ignored and the command line value used\n'
                     'instead. VALUE can be 0, in which case all existing\n'
                     'snapshots will be deleted and no new snapshot will be\n'
                     'created')

parser.add_argument('-v', '--verbose', action="store_true",
		help='Echo the commands that are issued')

parser.add_argument('-d', '--delete-only', action="store_true",
                help='Do not make a new snapshot, but delete any old\nsurplus snapshots found')

parser.add_argument('-n', '--dry-run', action="store_true",
		help='Only echo the commands that would be issued,\ndo not actually do anything')

parser.add_argument('-o', '--only', action='append', metavar='FS', type=str,
                help='Only consider filesystems below FS. Can be given multiple times')

args = parser.parse_args()

TIME_FORMAT="%Y-%m-%d-%H:%M"

zfs = which("zfs")

if not zfs:
    raise Exception("No 'zfs' executable found in your PATH")

def mutative_cmd(cmdargs):
    if args.verbose or args.dry_run:
        print(" ".join(cmdargs))
    if not args.dry_run:
        check_call(cmdargs)

only = []
if args.only:
    for o in args.only:
        only.extend(["-r", o])

zfs_props = Popen([zfs, "get", "-t", "filesystem", "autosnapshot:{0}".format(args.tagname), "-H"] + only,
        stdout=PIPE)

encoding = locale.getdefaultlocale()[1]

for line in zfs_props.stdout:
    fs, prop, value, source = line.decode(encoding).split("\t")
    try:
        number, minutes = value.split(",")
    except:
        number = value
        minutes = None
    if number != "-" and number != "none":
        snapshots = []

        zfs_snapshots = Popen([zfs, "list", "-t", "snapshot", "-d", "1", fs, "-H"], stdout=PIPE)

        for line_snapshots in zfs_snapshots.stdout:
            snapname, rest = line_snapshots.decode(encoding).split("\t", 1)
            if snapname.startswith("{0}@autosnapshot-{1}-".format(fs, args.tagname)):
                snapshots.append(snapname)

        if not args.delete_only:
            if minutes is not None and len(snapshots) > 0:
                # Round time now to format used
                now = time.strptime(time.strftime(TIME_FORMAT, time.gmtime()), TIME_FORMAT)

                newest_time = time.strptime(snapshots[-1][len("{0}@autosnapshot-{1}-".format(fs, args.tagname)):], TIME_FORMAT)
                age = (time.mktime(now) - time.mktime(newest_time))

                if int(minutes) > age/60:
                    if args.verbose or args.dry_run:
                        print("No snapshot for {0}, last snapshot is only {1:.0f} minutes old, less than the configured {2}".format(
                                fs, age/60, minutes))
                    continue

            # Create new snapshot
            new_snapshot = "{0}@autosnapshot-{1}-{2}".format(fs, args.tagname,
                                time.strftime(TIME_FORMAT, time.gmtime()))
            mutative_cmd([zfs, "snapshot", new_snapshot])

        # Delete oldest snapshots
        if number == "keep-all":
            continue
        else:
            number = int(number)

        if number <= 0:
            raise Exception("Invalid number for property 'autosnapshot:{0}' on filesystem {1}: {2}".format(args.tagname, fs, number))

        snapshots.append(new_snapshot)
        to_delete = snapshots[:-number]

        for d in to_delete:
            # Delete this old snapshot
            if not d.startswith("{0}@autosnapshot-{1}-".format(fs, args.tagname)):
                raise Exception("Invalid snapshot name '{0}', does not start with '{1}@autosnapshot-{2}-'".format(d, fs, args.tagname))
            mutative_cmd([zfs, "destroy", d])