#!/usr/bin/python3
#
# Copyright 2024 Lorenz Hüdepohl
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation, either version 3 of the License, or (at your
# option) any later version.

# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
# more details.

# You should have received a copy of the GNU General Public License along
# with this program. If not, see <https://www.gnu.org/licenses/>.
#
import re
import shlex
import sys
import argparse
import textwrap
from typing import Iterable, Union, Optional, NoReturn
from subprocess import Popen, PIPE, run, CompletedProcess, CalledProcessError

__version__ = "0.4"
__version_info__ = tuple(__version__.split("."))

sys.tracebacklimit = 0

parser = argparse.ArgumentParser(
    description='This utility uses zfs send/receive to transfer snapshots from '
                'one zfs pool/filesytem to another. If preexisting snapshots with the same '
                'name exist on both sides they are assumed to hold identical state and only '
                'incremental send and receives are done to reduce the amount of data transferred.',
    formatter_class=argparse.ArgumentDefaultsHelpFormatter,
    fromfile_prefix_chars='@'
)

parser.add_argument("origin", type=str,
                    help='Origin zfs filesystem, could be an SSH remote path, e.g. "user@host:pool/fs". '
                         'As with scp, it is remote if there is no "/" before the first ":", '
                         'IPv6 addresses have to be put in brackets, e.g. "[::1]:pool/fs"')

parser.add_argument("destination", type=str,
                    help='Destination prefix, e.g. backup_pool/this_host. The ZFS snapshots from "origin" '
                         'are then stored below there. As with "origin", can be an SSH remote path')

parser.add_argument('-b', '--bidirectional', action="store_true",
                    help='Sync in both directions.')

parser.add_argument('--snapname', metavar="TAGNAME", type=str, action="append",
                    help='Only consider snapshot names starting with TAGNAME. '
                         'Can be specified more than once')

parser.add_argument('--ignore-snapname', metavar="TAGNAME", type=str, action="append",
                    help='Do not consider snapshot names starting with TAGNAME. '
                         'Can be specified more than once')

parser.add_argument('--ignore-filesystem', metavar="FSNAME", type=str, action="append",
                    help='Do not consider filesystem FSNAME (and its children). '
                         'Can be specified more than once')

parser.add_argument('-w', '--raw', action="store_true",
                    help='Pass -w/--raw to zfs send for encrypted source filesystems')

parser.add_argument('-v', '--verbose', action="append_const", const=1,
                    help='Echo the commands that are issued. Two -v pass a -v along to the zfs send/receive commands')

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

parser.add_argument('-F', '--force', action="store_true",
                    help='Pass `-F` to `zfs receive` to overwrite other '
                         'snapshots or diverged changes on the remote side\n')

parser.add_argument('-z', '--compression', action="store_true",
                    help='Pass "-C" to ssh')

parser.add_argument('--hold', action="store_true",
                    help='Keep a hold (zfs hold) on the most recent common snapshot on both sides, so that it '
                         'cannot be destroyed, e.g. by snapshot rotation, which would prevent further incremental '
                         'transfers. Holds of previous runs are released (zfs release). The hold tag is '
                         '"zfs-sync:" followed by the location of the other side, as given on the command line. '
                         'Requires the "hold" and "release" permissions')

parser.add_argument('--version', action='version', version=__version__)

args = parser.parse_args()
args.verbose = sum(args.verbose) if args.verbose is not None else 0

if args.verbose > 1:
    verbose = ["-v"]
else:
    verbose = []

if args.force:
    force = ["-F"]
else:
    force = []

if args.raw:
    raw = ["--raw"]
else:
    raw = []

if args.compression:
    compression = ["-C"]
else:
    compression = []


def ignore_filesystem(fs: str) -> bool:
    if args.ignore_filesystem:
        for ignore_fs in args.ignore_filesystem:
            if fs == ignore_fs or fs.startswith(ignore_fs + "/"):
                return True
    return False


def use_snapshot(snapname: str) -> bool:
    if args.ignore_snapname:
        for ignore_snapname in args.ignore_snapname:
            if snapname.startswith(ignore_snapname):
                return False

    if args.snapname:
        for allowed_snapname in args.snapname:
            if snapname.startswith(allowed_snapname):
                return True
        return False

    return True


def parse_location(location: str) -> tuple[str, str]:
    """Split "[user@]host:dataset" into (host, dataset), host is "" for local datasets"""
    # IPv6 addresses in brackets: "[user@][::1]:dataset"
    m = re.fullmatch(r"([^@/:\[\]]+@)?\[([^/\[\]]+)\]:(.*)", location)
    if m:
        host, dataset = (m[1] or "") + m[2], m[3]
    else:
        # Like scp: only remote if there is no "/" before the first ":",
        # so local datasets may contain ":" as well
        host, sep, dataset = location.partition(":")
        if not sep or "/" in host:
            return "", location
    if not host or host.startswith("-") or host.endswith("@") or not dataset:
        parser.error("invalid location '{0}', expected [user@]host:dataset".format(location))
    return host, dataset


def exit(code: int) -> NoReturn:
    if 'pdb' in sys.modules:
        raise RuntimeError()
    else:
        raise SystemExit(code)


def check_returncode(proc: Union[CompletedProcess, Popen]) -> None:
    if not proc.returncode == 0:
        assert isinstance(proc.args, list)
        print("Command \"{0}\" returned error {1}, aborting...".format(shlex.join(proc.args), proc.returncode),
              file=sys.stderr)
        if proc.stderr is not None:
            stderr = proc.stderr if isinstance(proc.stderr, (str, bytes)) else proc.stderr.read()
            if isinstance(stderr, bytes):
                stderr = stderr.decode(errors="replace")
            print(stderr, file=sys.stderr, end="")
        exit(2)


def do(cmd: list[str]) -> None:
    if args.verbose or args.dry_run:
        print(shlex.join(cmd), flush=True)
    if not args.dry_run:
        p = run(cmd)
        check_returncode(p)


class Snapshot(object):
    def __init__(self, fs: "Filesystem", name: str, guid: int):
        self.fs = fs
        self.name = name
        self.guid = guid
        self.holds: set[str] = set()

    def rename(self, newname: str):
        do(self.fs.state.command(["zfs", "rename",
                                  self.fs.name + "@" + self.name,
                                  self.fs.name + "@" + newname]))
        self.name = newname

    def __repr__(self):
        return "Snapshot({0}, '{1}', {2})".format(self.fs, self.name, self.guid)


class Filesystem(object):
    def __init__(self, state: "ZFSState", name: str, encryption: Optional[str] = None,
                 receive_resume_token: Optional[str] = None):
        self.state = state
        self.name = name
        self.encryption: bool = encryption is not None and encryption != "off"
        self.receive_resume_token: Optional[str] = None
        self.receive_resume_token_info: Optional[dict] = None
        if receive_resume_token != "-":
            self.receive_resume_token = receive_resume_token
        self.snapshots: list[Snapshot] = []
        self.snapshots_by_guid: dict[int, Snapshot] = {}
        # Including those excluded by --snapname/--ignore-snapname, in order
        self.all_snapshots: list[Snapshot] = []
        if self.receive_resume_token is not None:
            p = run(["zstream", "token", self.receive_resume_token], stdout=PIPE, stderr=PIPE, universal_newlines=True)
            if p.returncode != 0 and "used in the initial send no longer exists" in p.stderr:
                # do not make use of this token, could be on receiving side
                self.receive_resume_token = None
            elif p.returncode != 0:
                print(p.stderr, file=sys.stderr)
                raise CalledProcessError(p.returncode, p.args, p.stdout, p.stderr)

            # "fromguid" is only present for incremental streams
            token_info_format = textwrap.dedent(r"""
                (?:\s+fromguid: (?P<fromguid>.*)
                )?\s+object: (?P<object>.*)
                \s+offset: (?P<offset>.*)
                \s+bytes: (?P<bytes>.*)
                \s+toguid: (?P<toguid>.*)
                \s+toname: '(?P<toname>.*)'""")[1:]
            g = re.match(token_info_format, p.stdout)
            if g is None:
                print("Cannot parse receive resume token information:", file=sys.stderr)
                print(p.stdout, file=sys.stderr)
                exit(1)
            else:
                self.receive_resume_token_info = g.groupdict()

    def suffix(self) -> str:
        return self.name[len(self.state.prefix):]

    def parent(self) -> str:
        return self.name.rsplit("/", 1)[0]

    def add_excluded_snapshot(self, snapname: str, guid: int) -> Snapshot:
        snapshot = Snapshot(self, snapname, guid)
        self.all_snapshots.append(snapshot)
        return snapshot

    def hold_only(self, keep: Snapshot) -> None:
        # Hold first, then release, so that one snapshot is held at all times
        tag = self.state.hold_tag
        if tag not in keep.holds:
            do(self.state.command(["zfs", "hold", tag, self.name + "@" + keep.name]))
            keep.holds.add(tag)
        for snapshot in self.all_snapshots:
            if snapshot is not keep and tag in snapshot.holds:
                do(self.state.command(["zfs", "release", tag, self.name + "@" + snapshot.name]))
                snapshot.holds.remove(tag)

    def add_snapshot(self, snapname: str, guid: int) -> Snapshot:
        snapshot = Snapshot(self, snapname, guid)
        self.all_snapshots.append(snapshot)
        self.snapshots.append(snapshot)
        self.snapshots_by_guid[snapshot.guid] = snapshot
        if snapshot.guid not in self.state.snapshots_by_guid:
            self.state.snapshots_by_guid[snapshot.guid] = set()
        self.state.snapshots_by_guid[snapshot.guid].add(snapshot)
        return snapshot

    def sync_snapshots_to(self, dest: "ZFSState") -> None:
        if not self.snapshots:
            return

        dest_fs: Optional[Filesystem] = None

        candidates = set()
        for snapshot in self.snapshots:
            if snapshot.guid in dest.snapshots_by_guid:
                for dest_snapshot in dest.snapshots_by_guid[snapshot.guid]:
                    candidates.add(dest_snapshot.fs)

        def claimed_by_other(c: "Filesystem") -> bool:
            # Does the origin filesystem with the same suffix as candidate c
            # also share snapshots with it? Then c is that one's copy, not a
            # renamed copy of ours (e.g. if ours is a local copy of that one)
            if c.suffix() == self.suffix():
                return False
            other = self.state.filesystems_by_fsname.get(self.state.prefix + c.suffix())
            return other is not None and any(guid in other.snapshots_by_guid for guid in c.snapshots_by_guid)

        candidates = {c for c in candidates if not claimed_by_other(c)}

        if len(candidates) == 1:
            dest_fs, = candidates

        elif len(candidates) > 1:
            # Select the one with the same suffix, if exists
            dest_fs = None
            for c in candidates:
                if c.suffix() == self.suffix():
                    dest_fs = c
                    break

            if dest_fs is None:
                print("Found more than one possible destination for filesystem '{0}', aborting:\n  - {1}".format(
                      self.name, "\n  - ".join(sorted(map(str, candidates)))),
                      file=sys.stderr)
                exit(1)
        else:  # A suitable snapshot does not exist at destination

            # But an empty filesystem?
            dest_fs = dest.filesystems_by_fsname.get(dest.prefix + self.suffix(), None)
            if dest_fs is None:
                # if not, create one
                dest_fs = dest.add_filesystem(dest.prefix + self.suffix())

        def unsynced(fs1: "Filesystem", fs2: "Filesystem") -> list[tuple[int, Snapshot]]:
            res = []
            for i, snapshot in enumerate(fs1.snapshots):
                if snapshot.guid not in fs2.snapshots_by_guid:
                    res.append((i, snapshot))
                else:
                    if len(res) > 0 and args.verbose > 1:
                        # This can be intentional, for example "thinning out" some
                        # very old snapshots to save space, somewhere. There is no
                        # way to recover them into the other filesystem that I am
                        # aware of. One could clone the previous common point on
                        # the other side and receive the missing snapshots into
                        # there, but it would never re-create the linear chain
                        print(f"\nINFO: There are some old snapshots missing from {fs2.name},:\n")
                        for _, snapshot in res:
                            print("  - {0}@{1} (guid {2})".format(snapshot.fs.name, snapshot.name, hex(snapshot.guid)))
                        print()

                    # In this case, we decide to forget everything before a common snapshot
                    res = []

            return res

        my_unsynced = unsynced(self, dest_fs)
        their_unsynced = unsynced(dest_fs, self)

        if len(my_unsynced) > 0 and len(their_unsynced) > 0:
            print("\nERROR: The snapshots have diverged on origin and destination:\n", file=sys.stderr)
            print(" Unsynchronized snapshots on", self.name, file=sys.stderr)
            for _, snapshot in my_unsynced:
                print("  - {0}@{1} (guid {2})".format(snapshot.fs.name, snapshot.name, hex(snapshot.guid)),
                      file=sys.stderr)
            print("", file=sys.stderr)
            print(" Unsynchronized snapshots on", dest_fs.name, file=sys.stderr)
            for _, snapshot in their_unsynced:
                print("  - {0}@{1} (guid {2})".format(snapshot.fs.name, snapshot.name, hex(snapshot.guid)),
                      file=sys.stderr)
            print("\nAborting", file=sys.stderr)
            exit(1)

        if args.force and len(my_unsynced) > 0:
            # 'zfs receive -F' rolls the destination back to the base of the
            # incremental stream (or replaces it entirely for a full stream),
            # destroying all later snapshots - including those excluded via
            # --snapname/--ignore-snapname, which the checks above cannot see
            first, _ = my_unsynced[0]
            if first > 0:
                base_guid = self.snapshots[first - 1].guid
                base_index = [s.guid for s in dest_fs.all_snapshots].index(base_guid)
                at_risk = dest_fs.all_snapshots[base_index + 1:]
            else:
                at_risk = dest_fs.all_snapshots
            if at_risk:
                print("\nERROR: Receiving into {0} with -F would destroy these snapshots:\n".format(dest_fs.name),
                      file=sys.stderr)
                for snapshot in at_risk:
                    print("  - {0}@{1} (guid {2})".format(snapshot.fs.name, snapshot.name, hex(snapshot.guid)),
                          file=sys.stderr)
                print("\nAborting", file=sys.stderr)
                exit(1)

        # All checks passed, only now modify the destination
        # Has it been renamed at destination?
        if dest_fs.suffix() != self.suffix():
            dest.rename_filesystem(dest_fs, self.suffix())

        # Apply possible renames to dest
        for dest_snapshot in dest_fs.snapshots:
            if dest_snapshot.guid in self.snapshots_by_guid:
                snapshot = self.snapshots_by_guid[dest_snapshot.guid]
                if dest_snapshot.name != snapshot.name:
                    dest_snapshot.rename(snapshot.name)

        def send(fs: "Filesystem", unsynced: Iterable[tuple[int, Snapshot]], dest_fs: "Filesystem"):
            for i, snapshot in unsynced:
                send_cmd = ["zfs", "send"] + verbose
                if dest_fs.receive_resume_token_info is not None:
                    token_info = dest_fs.receive_resume_token_info
                    if i > 0:
                        # expect incremental
                        if token_info["fromguid"] is None or int(token_info["fromguid"]) != fs.snapshots[i - 1].guid:
                            print("Invalid receive resume token, does not match expected 'from' snapshot", file=sys.stderr)
                            exit(1)
                    else:
                        if token_info["fromguid"] is not None:
                            print("Invalid receive resume token, not expecting an incremental snapshot", file=sys.stderr)
                            exit(1)
                    if int(token_info["toguid"]) != snapshot.guid:
                        print("Invalid receive resume token, does not match expected 'to' snapshot", file=sys.stderr)
                        exit(1)
                    assert dest_fs.receive_resume_token is not None
                    send_cmd += ["-t", dest_fs.receive_resume_token]
                else:
                    if fs.encryption:
                        send_cmd += raw
                    if i > 0:
                        send_cmd += ["-i", "@" + fs.snapshots[i - 1].name]
                    send_cmd += [fs.name + "@" + snapshot.name]

                send_cmd = fs.state.command(send_cmd)
                recv_cmd = dest_fs.state.command(["zfs", "receive", "-s"] + force + verbose + ["-u", dest_fs.name])

                if args.verbose or args.dry_run:
                    print(shlex.join(send_cmd), "|", shlex.join(recv_cmd), flush=True)

                if not args.dry_run:
                    with Popen(send_cmd, stdout=PIPE) as p1:
                        with Popen(recv_cmd, stdin=p1.stdout) as p2:
                            if p1.stdout is not None:
                                p1.stdout.close()
                            p2.wait()
                            check_returncode(p2)
                            p1.wait()
                            check_returncode(p1)

                # Clear potential resume tokens
                dest_fs.receive_resume_token = None
                dest_fs.receive_resume_token_info = None

                # Update internal state
                dest_fs.add_snapshot(snapshot.name, snapshot.guid)

        if len(my_unsynced) > 0:
            send(self, my_unsynced, dest_fs)

        if args.hold:
            common = [snapshot for snapshot in self.snapshots if snapshot.guid in dest_fs.snapshots_by_guid]
            if common:
                self.hold_only(common[-1])
                dest_fs.hold_only(dest_fs.snapshots_by_guid[common[-1].guid])

    def __repr__(self):
        return "Filesystem({0}, '{1}')".format(self.state, self.name)


class ZFSState(object):
    def __init__(self, location: str, hold_tag: str, must_exist: bool = True):
        self.location = location
        self.hold_tag = hold_tag
        self.host, self.prefix = parse_location(location)

        self.filesystems: list[Filesystem] = []
        self.filesystems_by_fsname: dict[str, Filesystem] = {}
        self.filesystems_by_parents: dict[str, set[Filesystem]] = {}
        self.snapshots_by_guid: dict[int, set[Snapshot]] = {}

        # List all filesystems and snapshots
        proc = run(self.command(["zfs", "list", "-H",
                                 "-t", "filesystem,volume,snapshot",
                                 "-o", "type,name,guid,encryption,receive_resume_token,userrefs",
                                 "-s", "creation",
                                 "-r", self.prefix]),
                   stdout=PIPE, stderr=PIPE, text=True)

        if proc.returncode == 1 and proc.stderr.endswith("dataset does not exist\n"):
            if must_exist:
                print("Error: '{0}' does not exist".format(location), file=sys.stderr)
                exit(1)
            # Destination does not exist (yet), will be created by the first receive
            return
        check_returncode(proc)

        for line in proc.stdout.splitlines():
            kind, name, _guid, encryption, receive_resume_token, userrefs = line.strip().split("\t")
            guid = int(_guid)
            if not name.startswith(self.prefix):
                print("Unexpexted {0}: \"{1}\", expected a string starting with \"{2}\"".format(
                      kind, name, self.prefix),
                      file=sys.stderr)
                exit(1)
            if kind in ("filesystem", "volume"):
                # New filesystem (volumes are treated like filesystems)
                if not ignore_filesystem(name):
                    self.add_filesystem(name, encryption, receive_resume_token)
            elif kind == "snapshot":
                pass
            else:
                print("Unexpexted ZFS object: '{0}' for '{1}'".format(kind, name), file=sys.stderr)
                exit(1)

        held: dict[str, Snapshot] = {}
        for line in proc.stdout.splitlines():
            kind, name, _guid, encryption, receive_resume_token, userrefs = line.strip().split("\t")
            guid = int(_guid)
            if kind in ("filesystem", "volume"):
                pass
            elif kind == "snapshot":
                fsname, snapname = name.split("@", 1)
                if ignore_filesystem(fsname):
                    continue

                fs = self.filesystems_by_fsname[fsname]

                if use_snapshot(snapname):
                    snapshot = fs.add_snapshot(snapname, guid)
                else:
                    snapshot = fs.add_excluded_snapshot(snapname, guid)
                if userrefs not in ("-", "0"):
                    held[name] = snapshot
            else:
                print("Unexpexted ZFS object: '{0}' for '{1}'".format(kind, name), file=sys.stderr)
                exit(1)

        if args.hold:
            self.load_holds(held)

    def __repr__(self):
        return "ZFSState('{0}')".format(self.location)

    def load_holds(self, held: dict[str, Snapshot]) -> None:
        names = list(held)
        chunk = 500  # keep the command line short enough
        for i in range(0, len(names), chunk):
            proc = run(self.command(["zfs", "holds", "-H"] + names[i:i + chunk]),
                       stdout=PIPE, stderr=PIPE, text=True)
            check_returncode(proc)
            for line in proc.stdout.splitlines():
                name, tag, _ = line.split("\t")
                held[name].holds.add(tag)

    def command(self, cmd: list[str]) -> list[str]:
        if not self.host:
            return cmd
        # ssh joins its arguments with spaces and passes the result to the
        # remote shell, so each one must be quoted (dataset names may contain
        # spaces, for example)
        return ["ssh"] + compression + [self.host, shlex.join(cmd)]

    def add_filesystem(self, name: str, encryption: Optional[str] = None,
                       receive_resume_token: Optional[str] = None) -> Filesystem:
        fs = Filesystem(self, name, encryption, receive_resume_token)
        self.filesystems.append(fs)
        self.filesystems_by_fsname[fs.name] = fs
        parent = fs.parent()
        if fs.parent() in self.filesystems_by_parents:
            self.filesystems_by_parents[parent].add(fs)
        else:
            self.filesystems_by_parents[parent] = {fs}
        return fs

    def rename_filesystem(self, fs: Filesystem, newsuffix: str) -> None:
        do(self.command(["zfs", "rename", fs.name, self.prefix + newsuffix]))
        self._rename_filesystem(fs, self.prefix + newsuffix)

    def _rename_filesystem(self, fs: Filesystem, newname: str) -> None:
        oldname = fs.name
        oldparent = fs.parent()

        fs.name = newname
        newparent = fs.parent()

        # Update filesystems_by_fsname
        del self.filesystems_by_fsname[oldname]
        self.filesystems_by_fsname[newname] = fs

        # Put this fs in the proper list of children for its new parent
        self.filesystems_by_parents[oldparent].remove(fs)
        if newparent not in self.filesystems_by_parents:
            self.filesystems_by_parents[newparent] = {fs}
        else:
            self.filesystems_by_parents[newparent].add(fs)

        # Track implicit rename of all children
        if oldname in self.filesystems_by_parents:
            children = self.filesystems_by_parents[oldname]
            for child in sorted(children, key=lambda fs: fs.name):
                if not child.name.startswith(oldname):
                    print("This shouldn't happen", file=sys.stderr)
                    exit(1)
                newchildname = newname + child.name[len(oldname):]
                self._rename_filesystem(child, newchildname)


def sync(a: ZFSState, b: ZFSState):
    # By name, so that parents are handled before their children
    # (creation order is not sufficient, e.g. after a 'zfs rename')
    for a_fs in sorted(a.filesystems, key=lambda fs: fs.name):
        a_fs.sync_snapshots_to(b)


def check_overlap(origin: str, destination: str) -> None:
    # Different host names could still be the same machine, but we cannot tell
    orig_host, orig_prefix = parse_location(origin)
    dest_host, dest_prefix = parse_location(destination)
    if orig_host != dest_host:
        return
    if orig_prefix == dest_prefix:
        parser.error("origin and destination are the same")
    if dest_prefix.startswith(orig_prefix + "/"):
        parser.error("destination '{0}' is inside origin '{1}'".format(destination, origin))
    if orig_prefix.startswith(dest_prefix + "/"):
        parser.error("origin '{0}' is inside destination '{1}'".format(origin, destination))


check_overlap(args.origin, args.destination)

orig = ZFSState(args.origin, hold_tag="zfs-sync:" + args.destination)
dest = ZFSState(args.destination, hold_tag="zfs-sync:" + args.origin, must_exist=False)

sync(orig, dest)
if args.bidirectional:
    sync(dest, orig)
