#!/usr/bin/env python3
# cronlist - list cron jobs with a human-readable explanation of each schedule
# Usage: cronlist [--file FILE] [--user USER] [--next]
import argparse, datetime, os, re, subprocess, sys

def explain_field(value, name, names):
    if value == "*":
        return None
    if value.startswith("*/"):
        n = value[2:]
        return {"minute": "every %s minutes" % n, "hour": "every %s hours" % n,
                "dom": "every %s days" % n, "month": "every %s months" % n,
                "dow": "every %s days of the week" % n}.get(name, "every %s" % n)
    if "," in value:
        parts = value.split(",")
        return "%s %s" % (name, " and ".join(parts))
    if "-" in value:
        lo, hi = value.split("-", 1)
        return "%s %s through %s" % (name, names.get(lo, lo), names.get(hi, hi))
    return "%s %s" % (name, names.get(value, value))

MONTHS = {"1": "January", "2": "February", "3": "March", "4": "April", "5": "May",
          "6": "June", "7": "July", "8": "August", "9": "September", "10": "October",
          "11": "November", "12": "December"}
DAYS = {"0": "Sunday", "1": "Monday", "2": "Tuesday", "3": "Wednesday",
        "4": "Thursday", "5": "Friday", "6": "Saturday", "7": "Sunday"}

def explain(minute, hour, dom, month, dow):
    if minute == "0" and hour != "*" and dom == "*" and month == "*" and dow == "*":
        h = int(hour) if hour.isdigit() else hour
        ampm = "am" if isinstance(h, int) and h < 12 else "pm"
        h12 = (h % 12) or 12 if isinstance(h, int) else h
        return "every day at %s:00 %s" % (h12, ampm)
    bits = []
    if minute == "0" and hour == "0" and dom == "*" and month == "*" and dow == "*":
        return "every day at midnight"
    if minute.startswith("*/"):
        bits.append("every %s minutes" % minute[2:])
    elif minute != "*":
        bits.append("at minute %s" % minute)
    if hour.startswith("*/"):
        bits.append("every %s hours" % hour[2:])
    elif hour != "*":
        bits.append("at hour %s" % hour)
    if dom != "*":
        bits.append("on day %s of the month" % dom)
    if month != "*":
        bits.append("in %s" % ", ".join(MONTHS.get(m, m) for m in month.split(",")))
    if dow != "*":
        bits.append("on %s" % ", ".join(DAYS.get(d, d) for d in dow.replace("7", "0").split(",")))
    if not bits:
        return "every minute"
    return ", ".join(bits)

SHORTCUTS = {"@reboot": "at system startup", "@yearly": "once a year, at midnight on Jan 1",
             "@annually": "once a year, at midnight on Jan 1", "@monthly": "once a month, at midnight on the 1st",
             "@weekly": "once a week, at midnight on Sunday", "@daily": "every day at midnight",
             "@midnight": "every day at midnight", "@hourly": "every hour, at minute 0"}

def parse_lines(text, is_system=False):
    jobs = []
    for raw in text.splitlines():
        line = raw.strip()
        if not line or line.startswith("#"):
            continue
        if re.match(r"^[A-Za-z_][A-Za-z0-9_]*\s*=", line):
            continue  # env assignment
        if line.startswith("@"):
            parts = line.split(None, 1)
            if len(parts) == 2:
                jobs.append((SHORTCUTS.get(parts[0], parts[0]), parts[1], raw))
            continue
        parts = line.split(None, 6 if is_system else 5)
        if len(parts) < (7 if is_system else 6):
            continue
        if is_system:
            minute, hour, dom, month, dow, _user = parts[:6]
            cmd = parts[6]
        else:
            minute, hour, dom, month, dow = parts[:5]
            cmd = parts[5]
        if not re.match(r"^[\d\*/,\-]+$", minute):
            continue
        jobs.append((explain(minute, hour, dom, month, dow), cmd, raw))
    return jobs

def selftest():
    import tempfile
    from pathlib import Path
    cron = "0 9 * * 1-5 /usr/bin/backup.sh\n*/15 * * * * /usr/bin/check.sh\n@daily /usr/bin/clean.sh\n"
    with tempfile.NamedTemporaryFile("w", suffix=".cron", delete=False) as f:
        f.write(cron); path = f.name
    try:
        out = subprocess.run([sys.executable, os.path.abspath(__file__), "--file", path],
                             capture_output=True, text=True)
        assert out.returncode == 0, out.stderr
        assert "Monday" in out.stdout or "weekday" in out.stdout.lower() or "1-5" in out.stdout
        assert "every 15 minutes" in out.stdout
        assert "backup.sh" in out.stdout and "clean.sh" in out.stdout
        print("cronlist selftest: PASS")
    finally:
        os.unlink(path)
    return 0

def main():
    ap = argparse.ArgumentParser(prog="cronlist",
        description="List cron jobs with a human-readable explanation of each schedule.")
    ap.add_argument("--file", help="read crontab from this file instead of crontab -l")
    ap.add_argument("--user", help="list another user's crontab (needs privileges)")
    ap.add_argument("--system", action="store_true", help="parse /etc/crontab format (has a user field)")
    ap.add_argument("--selftest", action="store_true", help="run built-in self-test and exit")
    a = ap.parse_args()
    if a.selftest:
        return selftest()
    if a.file:
        text = open(a.file).read()
        jobs = parse_lines(text, is_system=a.system)
        src = a.file
    else:
        cmd = ["crontab", "-l"]
        if a.user:
            cmd += ["-u", a.user]
        r = subprocess.run(cmd, capture_output=True, text=True)
        if r.returncode != 0:
            if "no crontab" in r.stderr:
                print("cronlist: no crontab for %s." % (a.user or "current user"))
                return 0
            print("cronlist: %s" % r.stderr.strip(), file=sys.stderr); return 1
        jobs = parse_lines(r.stdout)
        src = "crontab%s" % (" (user %s)" % a.user if a.user else "")
    if not jobs:
        print("cronlist: no cron jobs in %s." % src); return 0
    print("cron jobs in %s (%d):" % (src, len(jobs)))
    for expl, cmdline, _raw in jobs:
        print("  %-55s %s" % (expl, cmdline))
    return 0

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