"""Takes a copy of one folder each evening, when the sun sets where you are."""

import argparse
import datetime as dt
import fcntl
import hashlib
import math
import os
import plistlib
import re
import shutil
import stat
import subprocess
import sys

HELP = """\
Takes a copy of one folder each evening, when the sun sets where you are.
Unchanged files are linked, not copied. Nothing is ever deleted.

usage: sunset.py COMMAND [options]

commands:
  when       print the sunset: --lat --lon [--date YYYY-MM-DD] [--days N]
  snap       take one snapshot now, at any hour
  tick       what the scheduler runs every 15 minutes
  verify     check a snapshot by restoring it: --dest [--snapshot NAME]
  install    write and load the scheduler unit (--print writes nothing)
  uninstall  unload and delete the unit that install wrote

snap, tick and install take:
  --src DIR   the folder to copy
  --dest DIR  an existing folder that holds the snapshots and sunset.log
  --lat DEG   latitude, -90 to 90, north positive
  --lon DEG   longitude, -180 to 180, east positive

Times are in this machine's zone, for a flat horizon at sea level.

normal is dead
"""

LABEL = "mom.normalisdead.sunset-snapshot"
UNIT_TEXT = "Daily copy of one folder. Hour set by the sun."
SNAP_NAME = re.compile(r"^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}$")
HEADING = re.compile(r"^Register of (.+)\. Latitude -?\d+\.\d\d\. Longitude -?\d+\.\d\d\.$")
DATED = re.compile(r"^(\d{4}-\d{2}-\d{2}) ")
CHUNK = 1 << 20
TEXT = {"encoding": "utf-8", "errors": "surrogateescape"}  # names are bytes on POSIX
TIMER = "sunset-snapshot.timer"


# The sun: NOAA Global Monitoring Laboratory solar calculator (spreadsheet formulas).

def _sunset_utc_minutes(day, lat, lon, minutes):
    """Sunset in minutes after 00:00 UTC of `day`, solved at that time of day, or None."""
    jd = day.toordinal() + 1721424.5 + minutes / 1440
    t = (jd - 2451545) / 36525
    l0 = (280.46646 + t * (36000.76983 + t * 0.0003032)) % 360
    m = math.radians(357.52911 + t * (35999.05029 - 0.0001537 * t))
    e = 0.016708634 - t * (0.000042037 + 0.0000001267 * t)
    c = (math.sin(m) * (1.914602 - t * (0.004817 + 0.000014 * t))
         + math.sin(2 * m) * (0.019993 - 0.000101 * t) + math.sin(3 * m) * 0.000289)
    omega = math.radians(125.04 - 1934.136 * t)
    app_long = math.radians(l0 + c - 0.00569 - 0.00478 * math.sin(omega))
    obliq0 = 23 + (26 + (21.448 - t * (46.815 + t * (0.00059 - t * 0.001813))) / 60) / 60
    obliq = math.radians(obliq0 + 0.00256 * math.cos(omega))
    decl = math.asin(math.sin(obliq) * math.sin(app_long))
    y = math.tan(obliq / 2) ** 2
    l0r = math.radians(l0)
    eq_time = 4 * math.degrees(
        y * math.sin(2 * l0r) - 2 * e * math.sin(m) + 4 * e * y * math.sin(m) * math.cos(2 * l0r)
        - 0.5 * y * y * math.sin(4 * l0r) - 1.25 * e * e * math.sin(2 * m))
    phi = math.radians(lat)
    cos_ha = (math.cos(math.radians(90.833)) / (math.cos(phi) * math.cos(decl))
              - math.tan(phi) * math.tan(decl))
    if not -1 <= cos_ha <= 1:
        return None  # polar day or polar night: no clamped guess
    return 720 - 4 * (lon - math.degrees(math.acos(cos_ha))) - eq_time


def _sunset_utc(day, lat, lon):
    first = _sunset_utc_minutes(day, lat, lon, 720)
    if first is None:
        return None
    again = _sunset_utc_minutes(day, lat, lon, first)
    if again is None:
        return None
    midnight = dt.datetime(day.year, day.month, day.day, tzinfo=dt.timezone.utc)
    return midnight + dt.timedelta(minutes=again)


def sunset(day, lat, lon, tz=None):
    """Minutes after local midnight of the sunset whose local date is `day`, or None.

    tz None means this machine's zone. The UTC event of a neighbouring date can land on `day`.
    """
    for offset in (-1, 0, 1):
        event = _sunset_utc(day + dt.timedelta(days=offset), lat, lon)
        if event is None:
            continue
        local = event.astimezone(tz)
        if local.date() == day:
            return min((local.hour * 3600 + local.minute * 60 + local.second + 30) // 60, 1439)
    return None


def hhmm(minutes):
    return f"{minutes // 60:02d}:{minutes % 60:02d}"


def sun_phrase(day, lat, lon, tz=None):
    s = sunset(day, lat, lon, tz)
    return "No sunset." if s is None else f"Sunset {hhmm(s)}."


# The destination.

class Refusal(Exception):
    """A plain refusal printed to stderr; never a log line."""


class Failure(Exception):
    """A failed snapshot; becomes `<sun> No snapshot. <reason>.`"""


def reason(err, rel=None):
    text = (err.strerror or str(err)).replace("\n", " ")
    return f"{text}: {rel}" if rel else text


def read_log(dest):
    try:
        with open(os.path.join(dest, "sunset.log"), **TEXT) as f:
            return f.read().splitlines()
    except FileNotFoundError:
        return None


def guard(src, dest, need_register):
    """Step 1 and 3, and the link probe. Writes nothing that stays."""
    if not os.path.isdir(dest):
        raise Refusal("Destination does not exist. Nothing was copied.")
    log = read_log(dest)
    if log is None and need_register:
        raise Refusal("Destination has no register. Nothing was copied.")
    if log is not None:
        head = HEADING.match(log[0]) if log else None
        if not head:
            raise Refusal("Destination has no register. Nothing was copied.")
        if head.group(1) != src:
            raise Refusal(f"Register is for {head.group(1)}. Nothing was copied.")
    rs, rd = os.path.realpath(src), os.path.realpath(dest)
    if rd == rs or rd.startswith(rs.rstrip("/") + "/"):
        raise Refusal("Destination is inside the source. Nothing was copied.")
    if rs.startswith(rd.rstrip("/") + "/"):
        raise Refusal("Source is inside the destination. Nothing was copied.")
    probe = os.path.join(dest, f".probe-{os.getpid()}")
    try:
        open(probe, "x").close()
    except OSError as err:
        raise Failure(reason(err))
    try:
        os.link(probe, probe + "-link")
    except OSError:
        raise Refusal("Destination cannot hard link. Nothing was copied.")
    finally:
        for p in (probe, probe + "-link"):
            try:
                os.unlink(p)
            except FileNotFoundError:
                pass
    return log


def take_lock(dest):
    """Exclusive, non-blocking. The lock dies with the process. Returns the open fd or None."""
    fd = os.open(os.path.join(dest, ".lock"), os.O_RDWR | os.O_CREAT, 0o644)
    try:
        fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
    except BlockingIOError:
        os.close(fd)
        return None
    return fd


def snapshots(dest):
    names = (n for n in os.listdir(dest) if SNAP_NAME.match(n))
    return sorted(n for n in names if os.path.isdir(os.path.join(dest, n)))


def clear_scratch(dest, prefix):
    for n in os.listdir(dest):
        if n.startswith(prefix):
            shutil.rmtree(os.path.join(dest, n))


# The manifest, in `sha256sum -c` format with GNU escaping.

def manifest_line(digest, rel):
    if "\\" in rel or "\n" in rel:
        return "\\" + digest + "  " + rel.replace("\\", "\\\\").replace("\n", "\\n")
    return digest + "  " + rel


def read_manifest(folder):
    out = {}
    try:
        with open(os.path.join(folder, "SUNSET.sha256"), **TEXT) as f:
            lines = f.read().split("\n")
    except FileNotFoundError:
        return out
    for line in lines:
        escaped = line.startswith("\\")
        line = line[1:] if escaped else line
        if len(line) < 67:
            continue
        rel = line[66:]
        if escaped:
            rel = re.sub(r"\\(.)", lambda m: "\n" if m.group(1) == "n" else m.group(1), rel)
        out[rel] = line[:64]
    return out


def hash_file(path):
    h = hashlib.sha256()
    with open(path, "rb") as f:
        while chunk := f.read(CHUNK):
            h.update(chunk)
    return h.hexdigest()


# The snapshot.

def same(a, b):
    """The rsync quick check, plus the mode with write bits ignored."""
    return (a.st_size == b.st_size and a.st_mtime_ns == b.st_mtime_ns
            and stat.S_IMODE(a.st_mode) & ~0o222 == stat.S_IMODE(b.st_mode) & ~0o222)


def store(path, st, dst, rel, prev, prev_hashes):
    """Link from the previous snapshot when unchanged, else copy and hash. Returns the hash."""
    if prev:
        old = os.path.join(prev, rel)
        try:
            ost = os.lstat(old)
        except FileNotFoundError:
            ost = None
        if ost and stat.S_ISREG(ost.st_mode) and same(st, ost):
            os.link(old, dst)
            return prev_hashes.get(rel) or hash_file(dst)
    h = hashlib.sha256()
    with open(path, "rb") as f, open(dst, "xb") as o:
        while chunk := f.read(CHUNK):
            h.update(chunk)
            o.write(chunk)
    shutil.copystat(path, dst, follow_symlinks=False)
    os.chmod(dst, stat.S_IMODE(os.lstat(dst).st_mode) & ~0o222)
    return h.hexdigest()


def copy_tree(src, part, prev):
    """Step 5 and 6. Directories made, symlinks recreated, regular files linked or copied."""
    prev_hashes = read_manifest(prev) if prev else {}
    hashes = {}
    stack = [""]
    while stack:
        rel_dir = stack.pop()
        try:
            with os.scandir(os.path.join(src, rel_dir)) as it:
                entries = sorted(it, key=lambda e: e.name)
        except OSError as err:
            raise Failure(reason(err, rel_dir))
        for entry in entries:
            rel = f"{rel_dir}/{entry.name}" if rel_dir else entry.name
            dst = os.path.join(part, rel)
            try:
                if entry.is_symlink():
                    os.symlink(os.readlink(entry.path), dst)
                elif entry.is_dir(follow_symlinks=False):
                    os.mkdir(dst)
                    stack.append(rel)
                elif entry.is_file(follow_symlinks=False):
                    st = entry.stat(follow_symlinks=False)
                    hashes[rel] = store(entry.path, st, dst, rel, prev, prev_hashes)
                # FIFOs, sockets and devices: not copied, not counted, not reported.
            except OSError as err:
                raise Failure(reason(err, rel))
    return hashes


def append_log(dest, lines):
    with open(os.path.join(dest, "sunset.log"), "a", **TEXT) as f:
        f.write("".join(line + "\n" for line in lines))


def missed_days(dest, last, today, log, lat, lon, tz):
    """`<date> <sun> No snapshot.` for each day since the last snapshot, before today, untraced."""
    if last is None:
        return []
    seen = {m.group(1) for m in map(DATED.match, log or []) if m}
    seen.update(n[:10] for n in snapshots(dest))
    after_last = dt.date.fromisoformat(last[:10]) + dt.timedelta(days=1)
    day = max(after_last, today - dt.timedelta(days=366))
    lines = []
    while day < today:
        if day.isoformat() not in seen:
            lines.append(f"{day} {sun_phrase(day, lat, lon, tz)} No snapshot.")
        day += dt.timedelta(days=1)
    return lines


def snap(src, dest, lat, lon, now, tz=None, from_tick=False):
    """One snapshot; returns the exit code. `now` is aware local time; tz None is local."""
    src, dest = os.path.abspath(src), os.path.abspath(dest)
    today = now.date()
    sun = sun_phrase(today, lat, lon, tz)
    try:
        log = guard(src, dest, need_register=from_tick)
    except Refusal as r:
        print(r, file=sys.stderr)
        return 1
    except Failure as f:
        print(f"{sun} No snapshot. {f}.", file=sys.stderr)
        return 1
    lock = take_lock(dest)
    if lock is None:
        if not from_tick:
            print("Another run is in progress.", file=sys.stderr)
        return 0 if from_tick else 1
    try:
        name = now.strftime("%Y-%m-%dT%H-%M")
        part = os.path.join(dest, ".partial-" + name)
        try:
            clear_scratch(dest, ".partial-")
            if os.path.lexists(os.path.join(dest, name)):
                print(f"Snapshot {now:%H:%M} exists.", file=sys.stderr)
                return 1
            done = snapshots(dest)
            prev = os.path.join(dest, done[-1]) if done else None
            os.mkdir(part)
            hashes = copy_tree(src, part, prev)
            manifest = os.path.join(part, "SUNSET.sha256")
            with open(manifest, "x", **TEXT) as f:
                f.write("".join(manifest_line(hashes[r], r) + "\n" for r in sorted(hashes)))
            os.chmod(manifest, 0o444)
            os.rename(part, os.path.join(dest, name))  # the commit
        except (OSError, Failure) as err:
            shutil.rmtree(part, ignore_errors=True)
            line = f"{sun} No snapshot. {err if isinstance(err, Failure) else reason(err)}."
            print(line, file=sys.stderr)
            if log is not None:
                dated = f"{today} {line}"
                if not log or log[-1] != dated:
                    append_log(dest, [dated])
            return 1
        n = len(hashes)
        line = f"{sun} Snapshot {now:%H:%M}. {n} file{'' if n == 1 else 's'}."
        missed = missed_days(dest, done[-1] if done else None, today, log, lat, lon, tz)
        for m in missed:
            print(m)
        print(line)
        heading = f"Register of {src}. Latitude {lat:.2f}. Longitude {lon:.2f}."
        head = [] if log is not None else [heading]
        append_log(dest, head + missed + [f"{today} {line}"])
        return 0
    finally:
        os.close(lock)


def tick(src, dest, lat, lon, now, tz=None):
    """The scheduler's whole brain. Silent unless it snapshots or refuses."""
    src, dest = os.path.abspath(src), os.path.abspath(dest)
    try:
        guard(src, dest, need_register=True)
    except Refusal as r:
        print(r, file=sys.stderr)
        return 1
    except Failure:
        pass  # snap reports it
    today = now.date()
    s = sunset(today, lat, lon, tz)
    threshold = 0 if s is None else s
    stamp = today.isoformat()
    for n in snapshots(dest):
        if n.startswith(stamp) and int(n[11:13]) * 60 + int(n[14:16]) >= threshold:
            return 0
    if now.hour * 60 + now.minute < threshold:
        return 0
    return snap(src, dest, lat, lon, now, tz, from_tick=True)


# The restore test.

def verify(dest, name=None):
    dest = os.path.abspath(dest)
    if not os.path.isdir(dest):
        print("Destination does not exist.", file=sys.stderr)
        return 1
    lock = take_lock(dest)
    if lock is None:
        print("Another run is in progress.", file=sys.stderr)
        return 1
    try:
        clear_scratch(dest, ".restore-")
        done = snapshots(dest)
        name = name or (done[-1] if done else None)
        if name not in done:
            print(f"No snapshot {name}." if name else "No snapshot to verify.", file=sys.stderr)
            return 1
        snap_dir = os.path.join(dest, name)
        expected = read_manifest(snap_dir)
        scratch = os.path.join(dest, ".restore-" + name)
        try:
            restored = restore(snap_dir, scratch)
        finally:
            shutil.rmtree(scratch, ignore_errors=True)
        matched, problems = 0, []
        for rel in sorted(set(expected) | set(restored)):
            if rel not in restored:
                problems.append(f"Missing: {rel}")
            elif rel not in expected:
                problems.append(f"Extra: {rel}")
            elif restored[rel] != expected[rel]:
                problems.append(f"Differs: {rel}")
            else:
                matched += 1
        for p in sorted(problems, key=lambda p: p.split(": ", 1)[1]):
            print(p)
        print(f"Restored {name}. {matched} of {len(expected)} files match.")
        return 0 if matched == len(expected) and not problems else 1
    finally:
        os.close(lock)


def restore(snap_dir, scratch):
    """Copy by plain reads and writes (no links), symlinks as symlinks, then hash what landed."""
    restored = {}
    os.mkdir(scratch)
    stack = [""]
    while stack:
        rel_dir = stack.pop()
        with os.scandir(os.path.join(snap_dir, rel_dir)) as it:
            entries = sorted(it, key=lambda e: e.name)
        for entry in entries:
            rel = f"{rel_dir}/{entry.name}" if rel_dir else entry.name
            if rel == "SUNSET.sha256":
                continue
            dst = os.path.join(scratch, rel)
            if entry.is_symlink():
                os.symlink(os.readlink(entry.path), dst)
            elif entry.is_dir(follow_symlinks=False):
                os.mkdir(dst)
                stack.append(rel)
            elif entry.is_file(follow_symlinks=False):
                try:
                    with open(entry.path, "rb") as f, open(dst, "xb") as o:
                        while chunk := f.read(CHUNK):
                            o.write(chunk)
                    restored[rel] = hash_file(dst)
                except OSError:
                    restored[rel] = None  # unreadable: listed as differing
    return restored


# The scheduler unit.

def tick_args(a):
    return [os.path.realpath(sys.executable), os.path.abspath(__file__), "tick",
            "--src", os.path.abspath(a.src), "--dest", os.path.abspath(a.dest),
            "--lat", str(a.lat), "--lon", str(a.lon)]


def launchd_plist(a):
    return plistlib.dumps({
        "Label": LABEL,
        "Comment": UNIT_TEXT,
        "ProgramArguments": tick_args(a),
        "StartCalendarInterval": [{"Minute": m} for m in (0, 15, 30, 45)],
        "RunAtLoad": True,
        "LowPriorityIO": True,
        "StandardErrorPath": os.path.expanduser("~/Library/Logs/sunset-snapshot.log"),
    }).decode()


def systemd_quote(s):
    s = s.replace("\\", "\\\\").replace('"', '\\"').replace("%", "%%").replace("$", "$$")
    return '"' + s + '"'


def systemd_units(a):
    service = (f"[Unit]\nDescription={UNIT_TEXT}\n\n[Service]\nType=oneshot\n"
               f"ExecStart={' '.join(systemd_quote(x) for x in tick_args(a))}\n")
    timer = (f"[Unit]\nDescription={UNIT_TEXT}\n\n[Timer]\nOnCalendar=*:0/15\nPersistent=true\n"
             "OnStartupSec=1min\n\n[Install]\nWantedBy=timers.target\n")
    return {"sunset-snapshot.service": service, TIMER: timer}


def unit_files(a=None):
    """{path: text} of the units this platform uses; text is None when `a` is None."""
    if sys.platform == "darwin":
        path = os.path.expanduser(f"~/Library/LaunchAgents/{LABEL}.plist")
        return {path: a and launchd_plist(a)}
    base = os.path.expanduser("~/.config/systemd/user")
    units = systemd_units(a) if a else dict.fromkeys(("sunset-snapshot.service", TIMER))
    return {os.path.join(base, n): text for n, text in units.items()}


def install(a, now, tz=None):
    files = unit_files(a)
    if a.print:
        headed = len(files) > 1  # systemd: two files, each under a comment naming it
        print("\n".join((f"# {os.path.basename(p)}\n" if headed else "") + t
                        for p, t in files.items()), end="")
        return 0
    for path, text in files.items():
        os.makedirs(os.path.dirname(path), exist_ok=True)
        with open(path, "w", encoding="utf-8") as f:
            f.write(text)
    if sys.platform == "darwin":
        target = f"gui/{os.getuid()}"
        subprocess.run(["launchctl", "bootout", f"{target}/{LABEL}"], capture_output=True)
        subprocess.run(["launchctl", "bootstrap", target, *files], check=True)
    else:
        subprocess.run(["systemctl", "--user", "daemon-reload"], check=True)
        subprocess.run(["systemctl", "--user", "enable", "--now", TIMER], check=True)
    today = now.date()
    s = sunset(today, a.lat, a.lon, tz)
    if s is not None and s >= now.hour * 60 + now.minute:
        print(f"Installed. Next sunset {hhmm(s)}.")
    else:
        tomorrow = today + dt.timedelta(days=1)
        print(f"Installed. {tomorrow} {sun_phrase(tomorrow, a.lat, a.lon, tz)}")
    print(f"Python {os.path.realpath(sys.executable)}.")
    return 0


def uninstall():
    files = [p for p in unit_files() if os.path.exists(p)]
    if not files:
        print("Nothing was installed.")
        return 0
    if sys.platform == "darwin":
        subprocess.run(["launchctl", "bootout", f"gui/{os.getuid()}/{LABEL}"], capture_output=True)
    else:
        subprocess.run(["systemctl", "--user", "disable", "--now", TIMER], capture_output=True)
    for p in files:
        os.unlink(p)
    if sys.platform != "darwin":
        subprocess.run(["systemctl", "--user", "daemon-reload"], capture_output=True)
    print("Uninstalled.")
    return 0


# The command line.

class Parser(argparse.ArgumentParser):
    def error(self, message):
        sys.stderr.write(message[0].upper() + message[1:] + ".\n")
        sys.exit(2)


class Help(argparse.Action):
    def __init__(self, **kw):
        super().__init__(nargs=0, default=argparse.SUPPRESS, **kw)

    def __call__(self, *_):
        sys.stdout.write(HELP)
        sys.exit(0)


def parse(argv):
    p = Parser(prog="sunset.py", add_help=False)
    p.add_argument("-h", "--help", action=Help)
    sub = p.add_subparsers(dest="command", required=True, metavar="COMMAND")

    def command(name, *flags):
        c = sub.add_parser(name, add_help=False)
        c.add_argument("-h", "--help", action=Help)
        for flag in flags:
            kind = {"--lat": float, "--lon": float, "--days": int, "--print": None}.get(flag, str)
            if kind is None:
                c.add_argument(flag, action="store_true")
            else:
                required = flag in ("--src", "--dest", "--lat", "--lon")
                c.add_argument(flag, type=kind, required=required, metavar=flag[2:].upper())
        return c

    place = ("--src", "--dest", "--lat", "--lon")
    command("when", "--lat", "--lon", "--date", "--days")
    command("snap", *place)
    command("tick", *place)
    command("verify", "--dest", "--snapshot")
    command("install", *place, "--print")
    command("uninstall")
    a = p.parse_args(argv)
    if hasattr(a, "lat") and not -90 <= a.lat <= 90:
        p.error("latitude must be between -90 and 90")
    if hasattr(a, "lon") and not -180 <= a.lon <= 180:
        p.error("longitude must be between -180 and 180")
    if getattr(a, "days", None) is not None and a.days < 1:
        p.error("days must be 1 or more")
    if getattr(a, "date", None) is not None:
        try:
            a.date = dt.date.fromisoformat(a.date)
        except ValueError:
            p.error("date must be YYYY-MM-DD")
    return a


def main(argv=None):
    a = parse(sys.argv[1:] if argv is None else argv)
    now = dt.datetime.now().astimezone()
    try:
        if a.command == "when":
            day = a.date or now.date()
            for i in range(a.days or 1):
                d = day + dt.timedelta(days=i)
                print(f"{d} {sun_phrase(d, a.lat, a.lon)}")
            return 0
        if a.command == "snap":
            return snap(a.src, a.dest, a.lat, a.lon, now)
        if a.command == "tick":
            return tick(a.src, a.dest, a.lat, a.lon, now)
        if a.command == "verify":
            return verify(a.dest, a.snapshot)
        if a.command == "install":
            return install(a, now)
        return uninstall()
    except OSError as err:
        print(f"{reason(err)}.", file=sys.stderr)
        return 1


if __name__ == "__main__":
    sys.exit(main())
