"""Tests for sunset.py. Run: uv run python -m unittest test_sunset

Every test makes its own temporary folders and files (under the system temp folder) and
removes them afterwards. None of it is a real backup. The clock is injected: no test waits.
"""

import contextlib
import datetime as dt
import errno
import io
import math
import os
import plistlib
import shutil
import stat
import subprocess
import sys
import tempfile
import time
import unittest
from argparse import Namespace
from unittest import mock
from zoneinfo import ZoneInfo

import sunset

HERE = os.path.dirname(os.path.abspath(__file__))
BERLIN = ZoneInfo("Europe/Berlin")
LAT, LON = 52.52, 13.40  # Berlin


def at(y, mo, d, h=0, mi=0, tz=BERLIN):
    return dt.datetime(y, mo, d, h, mi, tzinfo=tz)


def usno_sunset_utc(day, lat, lon):
    """Independent cross-check: the U.S. Naval Observatory's 'Almanac for Computers' (1990)
    sunset algorithm, zenith 90.833 degrees. A different method from NOAA's; agrees to about
    a minute at mid latitudes. Returns hours UTC."""
    rad, deg = math.radians, math.degrees
    n = day.timetuple().tm_yday
    lng_hour = lon / 15
    t = n + (18 - lng_hour) / 24
    m = 0.9856 * t - 3.289
    lng = (m + 1.916 * math.sin(rad(m)) + 0.020 * math.sin(rad(2 * m)) + 282.634) % 360
    ra = deg(math.atan(0.91764 * math.tan(rad(lng)))) % 360
    ra = (ra + (lng // 90) * 90 - (ra // 90) * 90) / 15
    sin_dec = 0.39782 * math.sin(rad(lng))
    cos_dec = math.cos(math.asin(sin_dec))
    cos_h = (math.cos(rad(90.833)) - sin_dec * math.sin(rad(lat))) / (cos_dec * math.cos(rad(lat)))
    h = deg(math.acos(cos_h)) / 15
    return (h + ra - 0.06571 * t - 6.622 - lng_hour) % 24


def gnu_sha256sum():
    try:
        r = subprocess.run(["sha256sum", "--version"], capture_output=True, text=True)
    except OSError:
        return False
    return "GNU" in r.stdout


class Sun(unittest.TestCase):
    def test_reference_greenwich_solstice(self):
        # Royal Observatory Greenwich, 51.4779 N 0 E, 2026-06-21, Europe/London (BST).
        # Reference: about 21:21 BST, the NOAA solar calculator value the concept card states
        # (unverified there). NOAA's online calculator was not consulted from this build, which
        # has no network; the independent USNO algorithm above is the second reference.
        day = dt.date(2026, 6, 21)
        got = sunset.sunset(day, 51.4779, 0, ZoneInfo("Europe/London"))
        self.assertLessEqual(abs(got - (21 * 60 + 21)), 2)
        usno = usno_sunset_utc(day, 51.4779, 0) * 60 + 60  # BST is UTC+1
        self.assertLessEqual(abs(got - usno), 2)

    def test_equinox_equator(self):
        # 0 N 0 E, 2026-03-20, UTC. NOAA's own value could not be fetched here (no network);
        # the reference is the USNO algorithm, within 3 minutes.
        day = dt.date(2026, 3, 20)
        got = sunset.sunset(day, 0, 0, dt.timezone.utc)
        self.assertLessEqual(abs(got - usno_sunset_utc(day, 0, 0) * 60), 3)
        self.assertEqual(sunset.hhmm(got), "18:11")

    def test_berlin_three_days(self):
        days = [dt.date(2026, 10, 13) + dt.timedelta(days=i) for i in range(3)]
        got = [sunset.hhmm(sunset.sunset(d, LAT, LON, BERLIN)) for d in days]
        self.assertEqual(got, ["18:16", "18:14", "18:12"])
        for d in days:  # and the independent method agrees within 2 minutes (CEST is UTC+2)
            usno = usno_sunset_utc(d, LAT, LON) * 60 + 120
            self.assertLessEqual(abs(sunset.sunset(d, LAT, LON, BERLIN) - usno), 2)

    def test_polar_day_and_night(self):
        oslo = ZoneInfo("Europe/Oslo")
        self.assertIsNone(sunset.sunset(dt.date(2026, 6, 21), 69.65, 18.96, oslo))
        self.assertIsNone(sunset.sunset(dt.date(2026, 12, 21), 69.65, 18.96, oslo))
        self.assertEqual(sunset.sun_phrase(dt.date(2026, 6, 21), 89.9, 0, oslo), "No sunset.")

    def test_event_crossing_the_local_date(self):
        # Kiritimati keeps UTC+14 at 157 W: the UTC date's event falls on the next local date,
        # so the sunset of a local date comes from the previous UTC date.
        kiri = ZoneInfo("Pacific/Kiritimati")
        day = dt.date(2026, 10, 13)
        self.assertNotEqual(sunset._sunset_utc(day, 1.87, -157.4).astimezone(kiri).date(), day)
        got = sunset.sunset(day, 1.87, -157.4, kiri)
        self.assertTrue(17 * 60 + 30 < got < 19 * 60 + 30, got)

    def test_when_command(self):
        code, out, _ = run_main(["when", "--lat", "52.52", "--lon", "13.40",
                                 "--date", "2026-10-13", "--days", "3"], tz="Europe/Berlin")
        self.assertEqual(code, 0)
        self.assertEqual(out, "2026-10-13 Sunset 18:16.\n2026-10-14 Sunset 18:14.\n"
                              "2026-10-15 Sunset 18:12.\n")


def run_main(argv, tz=None, env=None):
    saved = dict(os.environ)
    if tz:
        os.environ["TZ"] = tz
    os.environ.update(env or {})
    time.tzset()
    out, err = io.StringIO(), io.StringIO()
    try:
        with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
            try:
                code = sunset.main(argv)
            except SystemExit as e:
                code = e.code
    finally:
        os.environ.clear()
        os.environ.update(saved)
        time.tzset()
    return code, out.getvalue(), err.getvalue()


class Box(unittest.TestCase):
    """A temporary source and destination made by the test."""

    lat, lon = LAT, LON

    def setUp(self):
        self.tmp = tempfile.mkdtemp(prefix="sunset-test-")
        self.src = os.path.join(self.tmp, "src")
        self.dest = os.path.join(self.tmp, "dest")
        os.makedirs(os.path.join(self.src, "sub"))
        os.mkdir(self.dest)
        self.write("a.txt", "alpha\n")
        self.write("sub/b.txt", "bravo\n")

    def tearDown(self):
        for root, dirs, files in os.walk(self.tmp):
            for name in files:
                p = os.path.join(root, name)
                if not os.path.islink(p):
                    os.chmod(p, 0o644)
        shutil.rmtree(self.tmp)

    def write(self, rel, text):
        with open(os.path.join(self.src, rel), "w") as f:
            f.write(text)

    def call(self, fn, *args, **kw):
        out, err = io.StringIO(), io.StringIO()
        with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
            code = fn(*args, **kw)
        return code, out.getvalue(), err.getvalue()

    def snap(self, now, src=None):
        return self.call(sunset.snap, src or self.src, self.dest, self.lat, self.lon, now, BERLIN)

    def tick(self, now, src=None):
        return self.call(sunset.tick, src or self.src, self.dest, self.lat, self.lon, now, BERLIN)

    def log(self):
        with open(os.path.join(self.dest, "sunset.log")) as f:
            return f.read().splitlines()

    def folders(self):
        return sunset.snapshots(self.dest)

    def listing(self):
        return sorted(os.listdir(self.dest)) if os.path.isdir(self.dest) else None

    def count(self):
        return sum(len(files) for _, _, files in os.walk(self.src))


class Snapshot(Box):
    def test_first_snap_writes_register_and_line(self):
        code, out, err = self.snap(at(2026, 10, 13, 12, 7))
        self.assertEqual((code, err), (0, ""))
        self.assertEqual(out, "Sunset 18:16. Snapshot 12:07. 2 files.\n")
        self.assertEqual(self.folders(), ["2026-10-13T12-07"])
        self.assertEqual(self.log(), [f"Register of {self.src}. Latitude 52.52. Longitude 13.40.",
                                      "2026-10-13 Sunset 18:16. Snapshot 12:07. 2 files."])
        self.snap(at(2026, 10, 13, 12, 8))
        self.assertEqual(len(self.log()), 3)
        self.assertEqual(sum(line.startswith("Register") for line in self.log()), 1)

    def test_same_minute_stops(self):
        self.snap(at(2026, 10, 13, 17, 45))
        code, _, err = self.snap(at(2026, 10, 13, 17, 45))
        self.assertEqual((code, err), (1, "Snapshot 17:45 exists.\n"))

    def test_link_rule_and_read_only(self):
        self.write("edited.txt", "original\n")
        self.write("same-size.txt", "12345\n")
        self.write("run.sh", "echo\n")
        self.snap(at(2026, 10, 13, 18, 30))
        p = lambda rel: os.path.join(self.src, rel)  # noqa: E731
        with open(p("edited.txt"), "a") as f:
            f.write("x\n")
        st = os.stat(p("same-size.txt"))
        self.write("same-size.txt", "54321\n")
        os.utime(p("same-size.txt"), ns=(st.st_atime_ns, st.st_mtime_ns + 5_000_000_000))
        st = os.stat(p("run.sh"))
        os.chmod(p("run.sh"), 0o755)
        self.assertEqual(os.stat(p("run.sh")).st_mtime_ns, st.st_mtime_ns)
        self.snap(at(2026, 10, 13, 18, 31))
        one, two = (os.path.join(self.dest, n) for n in self.folders())
        ino = lambda d, rel: os.stat(os.path.join(d, rel)).st_ino  # noqa: E731
        self.assertEqual(ino(one, "a.txt"), ino(two, "a.txt"))
        self.assertEqual(ino(one, "sub/b.txt"), ino(two, "sub/b.txt"))
        for rel in ("edited.txt", "same-size.txt", "run.sh"):
            self.assertNotEqual(ino(one, rel), ino(two, rel), rel)
        with open(os.path.join(one, "edited.txt")) as f:
            self.assertEqual(f.read(), "original\n")
        self.assertTrue(os.stat(os.path.join(two, "run.sh")).st_mode & 0o100)
        for folder in (one, two):
            for root, _, files in os.walk(folder):
                for name in files:
                    mode = os.lstat(os.path.join(root, name)).st_mode
                    self.assertEqual(mode & 0o222, 0, name)

    def test_symlink_and_fifo(self):
        os.symlink("sub/b.txt", os.path.join(self.src, "link"))
        os.mkfifo(os.path.join(self.src, "pipe"))
        code, out, _ = self.snap(at(2026, 10, 13, 18, 30))
        self.assertEqual(code, 0)
        self.assertTrue(out.endswith(" 2 files.\n"), out)
        snap_dir = os.path.join(self.dest, self.folders()[0])
        self.assertFalse(os.path.lexists(os.path.join(snap_dir, "pipe")))
        self.assertEqual(os.readlink(os.path.join(snap_dir, "link")), "sub/b.txt")
        with open(os.path.join(snap_dir, "SUNSET.sha256")) as f:
            self.assertEqual(len(f.read().splitlines()), 2)

    def test_manifest_escaping(self):
        self.write("back\\slash", "1\n")
        self.write("new\nline", "2\n")
        self.snap(at(2026, 10, 13, 18, 30))
        snap_dir = os.path.join(self.dest, self.folders()[0])
        with open(os.path.join(snap_dir, "SUNSET.sha256")) as f:
            text = f.read()
        self.assertIn("\\" + sunset.hash_file(os.path.join(self.src, "back\\slash"))
                      + "  back\\\\slash\n", text)
        self.assertIn("  new\\nline\n", text)
        self.assertEqual(set(sunset.read_manifest(snap_dir)),
                         {"a.txt", "sub/b.txt", "back\\slash", "new\nline"})
        if gnu_sha256sum():  # BSD sha256sum skips escaped lines
            r = subprocess.run(["sha256sum", "-c", "SUNSET.sha256"], cwd=snap_dir,
                               capture_output=True, text=True)
            self.assertEqual((r.returncode, r.stderr), (0, ""))
            self.assertEqual(r.stdout.count(": OK\n"), 4)

    @unittest.skipIf(os.geteuid() == 0, "root ignores mode 000")
    def test_permission_denied(self):
        self.snap(at(2026, 2, 26, 12, 0))
        shutil.rmtree(os.path.join(self.dest, self.folders()[0]))  # no earlier snapshot
        self.write("secret.txt", "s\n")
        os.chmod(os.path.join(self.src, "secret.txt"), 0)
        for minute in (10, 15):
            code, out, err = self.tick(at(2026, 2, 27, 19, minute))
            self.assertEqual((code, out), (1, ""))
            self.assertEqual(err, "Sunset 17:42. No snapshot. Permission denied: secret.txt.\n")
            self.assertEqual(self.folders(), [])
            self.assertFalse([n for n in os.listdir(self.dest) if n.startswith(".partial-")])
        dated = "2026-02-27 Sunset 17:42. No snapshot. Permission denied: secret.txt."
        self.assertEqual(self.log().count(dated), 1)
        self.assertEqual(self.log()[-1], dated)
        # the next day succeeds, and the failed day gets no second line
        os.chmod(os.path.join(self.src, "secret.txt"), 0o644)
        code, out, _ = self.tick(at(2026, 2, 28, 19, 10))
        self.assertEqual(code, 0)
        self.assertEqual(sum(line.startswith("2026-02-27") for line in self.log()), 1)

    def test_failed_day_then_success(self):
        if os.geteuid() == 0:
            self.skipTest("root ignores mode 000")
        self.snap(at(2026, 2, 25, 19, 0))
        os.chmod(os.path.join(self.src, "sub"), 0)
        self.assertEqual(self.tick(at(2026, 2, 26, 19, 0))[0], 1)
        os.chmod(os.path.join(self.src, "sub"), 0o755)
        code, out, _ = self.tick(at(2026, 2, 27, 19, 10))
        self.assertEqual(code, 0)
        self.assertEqual(out, "Sunset 17:42. Snapshot 19:10. 2 files.\n")
        sun = sunset.sun_phrase(dt.date(2026, 2, 26), LAT, LON, BERLIN)
        day = [line for line in self.log() if line.startswith("2026-02-26")]
        self.assertEqual(day, [f"2026-02-26 {sun} No snapshot. Permission denied: sub."])


class Tick(Box):
    def setUp(self):
        super().setUp()
        self.snap(at(2026, 2, 26, 12, 0))  # registers the destination

    def test_before_and_after_sunset(self):
        self.assertEqual(self.tick(at(2026, 2, 27, 17, 30)), (0, "", ""))
        self.assertEqual(self.tick(at(2026, 2, 27, 17, 41)), (0, "", ""))
        self.assertEqual(len(self.folders()), 1)
        code, out, err = self.tick(at(2026, 2, 27, 19, 10))
        self.assertEqual((code, out, err), (0, "Sunset 17:42. Snapshot 19:10. 2 files.\n", ""))
        self.assertEqual(self.log()[-1], "2026-02-27 Sunset 17:42. Snapshot 19:10. 2 files.")
        self.assertEqual(self.tick(at(2026, 2, 27, 19, 15)), (0, "", ""))
        self.assertEqual(self.tick(at(2026, 2, 27, 23, 45)), (0, "", ""))
        self.assertEqual(len(self.folders()), 2)

    def test_at_sunset_minute(self):
        code, out, _ = self.tick(at(2026, 2, 27, 17, 42))
        self.assertEqual(out, "Sunset 17:42. Snapshot 17:42. 2 files.\n")

    def test_morning_snap_does_not_block_evening(self):
        self.snap(at(2026, 2, 27, 9, 0))
        code, out, _ = self.tick(at(2026, 2, 27, 17, 45))
        self.assertEqual(out, "Sunset 17:42. Snapshot 17:45. 2 files.\n")
        self.assertEqual(self.folders()[-2:], ["2026-02-27T09-00", "2026-02-27T17-45"])

    def test_missed_days(self):
        code, out, _ = self.tick(at(2026, 3, 2, 19, 0))
        self.assertEqual(code, 0)
        missed = [line for line in self.log() if "No snapshot." in line]
        self.assertEqual([line[:10] for line in missed], ["2026-02-27", "2026-02-28", "2026-03-01"])
        self.assertEqual(missed[0], "2026-02-27 Sunset 17:42. No snapshot.")
        for line in missed:
            self.assertRegex(line, r"^\d{4}-\d\d-\d\d Sunset \d\d:\d\d\. No snapshot\.$")
            self.assertIn(line, out)
        self.assertFalse([line for line in self.log() if line[:10] < "2026-02-26"
                          and not line.startswith("Register")])
        self.assertEqual(self.log()[-1][:10], "2026-03-02")

    def test_lock_held_by_tick_is_silent(self):
        fd = sunset.take_lock(self.dest)
        try:
            self.assertIsNone(sunset.take_lock(self.dest))
            self.assertEqual(self.tick(at(2026, 2, 27, 19, 10)), (0, "", ""))
            self.assertEqual(self.snap(at(2026, 2, 27, 19, 10))[2], "Another run is in progress.\n")
        finally:
            os.close(fd)


class Polar(Box):
    lat, lon = 89.9, 0.0

    def test_no_sunset_snapshot_at_midnight_then_tick_silent(self):
        os.remove(os.path.join(self.src, "sub/b.txt"))
        code, out, _ = self.snap(at(2026, 6, 20, 0, 0))
        self.assertEqual(out, "No sunset. Snapshot 00:00. 1 file.\n")
        self.assertEqual(self.folders(), ["2026-06-20T00-00"])
        self.assertEqual(self.tick(at(2026, 6, 20, 12, 0)), (0, "", ""))
        self.assertEqual(self.folders(), ["2026-06-20T00-00"])
        # two days off, then the first firing of the day
        code, out, _ = self.tick(at(2026, 6, 23, 0, 0))
        self.assertEqual(out, "2026-06-21 No sunset. No snapshot.\n2026-06-22 No sunset. "
                              "No snapshot.\nNo sunset. Snapshot 00:00. 1 file.\n")
        self.assertEqual(self.log()[-1], "2026-06-23 No sunset. Snapshot 00:00. 1 file.")


class Refusals(Box):
    def assertRefused(self, result, message, before):
        code, out, err = result
        self.assertEqual((code, out, err), (1, "", message + "\n"))
        self.assertEqual(self.listing(), before)

    def test_destination_inside_source(self):
        inner = os.path.join(self.src, "backup")
        os.mkdir(inner)
        before = sorted(os.listdir(self.src))
        result = self.call(sunset.snap, self.src, inner, LAT, LON, at(2026, 10, 13, 19), BERLIN)
        self.assertEqual(result, (1, "", "Destination is inside the source. Nothing was copied.\n"))
        self.assertEqual(sorted(os.listdir(self.src)), before)
        self.assertEqual(os.listdir(inner), [])

    def test_source_inside_destination(self):
        inner = os.path.join(self.dest, "docs")
        os.mkdir(inner)
        self.assertRefused(self.snap(at(2026, 10, 13, 19), src=inner),
                           "Source is inside the destination. Nothing was copied.", ["docs"])

    def test_cannot_hard_link(self):
        with mock.patch("os.link", side_effect=OSError(errno.EPERM, "Operation not permitted")):
            self.assertRefused(self.snap(at(2026, 10, 13, 19)),
                               "Destination cannot hard link. Nothing was copied.", [])

    def test_destination_missing(self):
        shutil.rmtree(self.dest)
        self.assertRefused(self.snap(at(2026, 10, 13, 19)),
                           "Destination does not exist. Nothing was copied.", None)

    def test_tick_into_unregistered(self):
        self.assertRefused(self.tick(at(2026, 10, 13, 19)),
                           "Destination has no register. Nothing was copied.", [])

    def test_log_without_heading(self):
        with open(os.path.join(self.dest, "sunset.log"), "w") as f:
            f.write("something else\n")
        for fn in (self.snap, self.tick):
            self.assertRefused(fn(at(2026, 10, 13, 19)),
                               "Destination has no register. Nothing was copied.", ["sunset.log"])

    def test_register_for_another_source(self):
        self.snap(at(2026, 10, 13, 12))
        other = os.path.join(self.tmp, "other")
        os.mkdir(other)
        before = self.listing()
        log = self.log()
        for fn in (self.snap, self.tick):
            self.assertRefused(fn(at(2026, 10, 13, 19), src=other),
                               f"Register is for {self.src}. Nothing was copied.", before)
        self.assertEqual(self.log(), log)

    def test_latitude_out_of_range(self):
        code, out, err = run_main(["snap", "--src", self.src, "--dest", self.dest,
                                   "--lat", "91", "--lon", "0"])
        self.assertEqual((code, out, err), (2, "", "Latitude must be between -90 and 90.\n"))
        self.assertEqual(self.listing(), [])

    def test_sigkill_leaves_no_final_folder(self):
        big = os.path.join(self.src, "big")
        os.mkdir(big)
        block = os.urandom(16384)
        for i in range(5000):
            with open(os.path.join(big, f"{i:05d}"), "wb") as f:
                f.write(block)
        self.snap(at(2026, 10, 13, 12))  # registers, then the killed run copies everything again
        shutil.rmtree(os.path.join(self.dest, self.folders()[0]))
        cmd = [sys.executable, os.path.join(HERE, "sunset.py"), "snap", "--src", self.src,
               "--dest", self.dest, "--lat", str(LAT), "--lon", str(LON)]
        proc = subprocess.Popen(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
        part = None
        deadline = time.monotonic() + 20
        while part is None and time.monotonic() < deadline:
            names = [n for n in os.listdir(self.dest) if n.startswith(".partial-")]
            if names and os.path.isdir(os.path.join(self.dest, names[0], "big")):
                part = names[0]
        proc.kill()
        proc.wait()
        self.assertIsNotNone(part)
        self.assertEqual(self.folders(), [])
        self.assertTrue(os.path.isdir(os.path.join(self.dest, part)))
        code = subprocess.run(cmd, capture_output=True).returncode
        self.assertEqual(code, 0)
        self.assertEqual(len(self.folders()), 1)
        self.assertFalse([n for n in os.listdir(self.dest) if n.startswith(".partial-")])


class Verify(Box):
    def setUp(self):
        super().setUp()
        self.outside = os.path.join(self.tmp, "outside")
        os.mkdir(self.outside)
        with open(os.path.join(self.outside, "far.txt"), "w") as f:
            f.write("not ours\n")
        os.symlink("a.txt", os.path.join(self.src, "rel"))
        os.symlink(self.outside, os.path.join(self.src, "out"))
        code, self.out, _ = self.snap(at(2026, 10, 13, 17, 45))
        self.name = self.folders()[0]

    def verify(self):
        return self.call(sunset.verify, self.dest)

    def test_restore_matches_and_cleans_up(self):
        os.makedirs(os.path.join(self.dest, ".restore-stale", "x"))
        code, out, err = self.verify()
        n = int(self.out.split(". ")[-1].split()[0])
        self.assertEqual(n, 2)
        self.assertEqual((code, out, err), (0, f"Restored {self.name}. 2 of 2 files match.\n", ""))
        self.assertFalse([x for x in os.listdir(self.dest) if x.startswith(".restore-")])

    def test_lock_held_by_another_process(self):
        holder = subprocess.Popen(
            [sys.executable, "-c", "import fcntl, sys; f = open(sys.argv[1], 'a'); "
             "fcntl.flock(f, fcntl.LOCK_EX); print('held', flush=True); sys.stdin.read()",
             os.path.join(self.dest, ".lock")],
            stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True)
        try:
            self.assertEqual(holder.stdout.readline(), "held\n")
            self.assertEqual(self.verify(), (1, "", "Another run is in progress.\n"))
        finally:
            holder.stdin.close()
            holder.wait()
            holder.stdout.close()

    def test_flipped_byte_is_named(self):
        path = os.path.join(self.dest, self.name, "sub", "b.txt")
        os.chmod(path, 0o644)
        with open(path, "r+b") as f:
            first = f.read(1)
            f.seek(0)
            f.write(bytes([first[0] ^ 1]))
        code, out, _ = self.verify()
        self.assertEqual(code, 1)
        self.assertEqual(out, f"Differs: sub/b.txt\nRestored {self.name}. 1 of 2 files match.\n")


class Unit(unittest.TestCase):
    args = Namespace(src="/srv/docs", dest="/mnt/backup/sunset", lat=52.52, lon=13.4, print=True)

    def test_launchd_plist(self):
        unit = plistlib.loads(sunset.launchd_plist(self.args).encode())
        self.assertEqual(unit["Label"], "mom.normalisdead.sunset-snapshot")
        self.assertEqual([d["Minute"] for d in unit["StartCalendarInterval"]], [0, 15, 30, 45])
        self.assertTrue(all(list(d) == ["Minute"] for d in unit["StartCalendarInterval"]))
        self.assertIs(unit["RunAtLoad"], True)
        self.assertEqual(unit["Comment"], "Daily copy of one folder. Hour set by the sun.")
        prog = unit["ProgramArguments"]
        self.assertEqual(prog[2:], ["tick", "--src", "/srv/docs", "--dest", "/mnt/backup/sunset",
                                    "--lat", "52.52", "--lon", "13.4"])
        self.assertEqual(subprocess.run([prog[0], prog[1], "--help"], capture_output=True)
                         .returncode, 0)

    def test_systemd_units(self):
        units = sunset.systemd_units(self.args)
        for text in units.values():
            self.assertIn("Description=Daily copy of one folder. Hour set by the sun.\n", text)
        timer = units["sunset-snapshot.timer"]
        self.assertIn("OnCalendar=*:0/15\n", timer)
        self.assertIn("Persistent=true\n", timer)
        self.assertIn('"tick" "--src" "/srv/docs"', units["sunset-snapshot.service"])
        self.assertEqual(sunset.systemd_quote('a "b" 100% $x'), '"a \\"b\\" 100%% $$x"')

    def test_install_print_writes_nothing(self):
        home = tempfile.mkdtemp(prefix="sunset-home-")
        try:
            code, out, _ = run_main(["install", "--print", "--src", "/srv/docs", "--dest",
                                     "/mnt/backup/sunset", "--lat", "52.52", "--lon", "13.4"],
                                    env={"HOME": home})
            self.assertEqual(code, 0)
            self.assertIn("Hour set by the sun.", out)
            self.assertEqual(os.listdir(home), [])
        finally:
            shutil.rmtree(home)


class Help(unittest.TestCase):
    def test_help_fits_a_terminal(self):
        code, out, _ = run_main(["--help"])
        lines = out.splitlines()
        self.assertEqual(code, 0)
        self.assertLessEqual(len(lines), 22)
        self.assertLessEqual(max(map(len, lines)), 80)
        self.assertEqual(lines[0], "Takes a copy of one folder each evening, "
                                   "when the sun sets where you are.")
        self.assertEqual(lines[-1], "normal is dead")
        self.assertNotIn("\x1b", out)


if __name__ == "__main__":
    unittest.main()
