#!/usr/bin/env python3
# touchdate — set a file's mtime to a given date, or copy it from another file; also shows what a file's date would be.
# Usage: touchdate [--date YYYY-MM-DD[ HH:MM[:SS]]] [--from FILE] [--atime] file [...]
"""touchdate: `touch -d` with guardrails. It parses a plain date (or full
timestamp), copies the date from a reference file, validates the result, and
prints the before/after mtime — so backdating a restored file is one explicit
command instead of a touch invocation you have to get exactly right."""
import argparse, datetime, os, sys

def parse_date(s):
    for fmt in ("%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M", "%Y-%m-%d", "%Y/%m/%d", "%Y-%m-%dT%H:%M:%S"):
        try: return datetime.datetime.strptime(s, fmt)
        except ValueError: pass
    raise ValueError(f"cannot parse date {s!r} (try YYYY-MM-DD or YYYY-MM-DD HH:MM:SS)")

def set_date(path, dt, atime_too=False):
    st = os.stat(path)
    old = datetime.datetime.fromtimestamp(st.st_mtime)
    ts = dt.timestamp()
    if atime_too: os.utime(path, (ts, ts))
    else: os.utime(path, (st.st_atime, ts))
    print(f"{path}: mtime {old} -> {dt}")
    return 0

def selftest():
    import tempfile
    with tempfile.TemporaryDirectory() as d:
        p = os.path.join(d, "f"); open(p, "w").write("x")
        assert set_date(p, parse_date("2001-02-03 04:05:06")) == 0
        assert datetime.datetime.fromtimestamp(os.stat(p).st_mtime).strftime("%Y-%m-%d %H:%M:%S") == "2001-02-03 04:05:06"
        r = os.path.join(d, "ref"); open(r, "w").write("y")
        os.utime(r, (0, 946684800))  # 2000-01-01
        dt = datetime.datetime.fromtimestamp(os.stat(r).st_mtime)
        assert set_date(p, dt) == 0
    print("touchdate selftest: PASS"); return 0

def main():
    ap = argparse.ArgumentParser(description="Set a file's mtime to a given date, or copy it from another file.")
    ap.add_argument("files", nargs="*", help="file(s) to retime")
    ap.add_argument("--date", help="date to set, e.g. 2020-01-15 or 2020-01-15 10:30:00")
    ap.add_argument("--from", dest="from_file", help="copy the mtime from this reference file")
    ap.add_argument("--atime", action="store_true", help="also set atime to the same value")
    ap.add_argument("--selftest", action="store_true")
    a = ap.parse_args()
    if a.selftest: return selftest()
    if not a.files: ap.error("need at least one file")
    if bool(a.date) == bool(a.from_file): ap.error("give exactly one of --date or --from")
    dt = parse_date(a.date) if a.date else datetime.datetime.fromtimestamp(os.stat(a.from_file).st_mtime)
    rc = 0
    for p in a.files:
        try: rc |= set_date(p, dt, a.atime)
        except OSError as e: print(f"touchdate: {p}: {e}", file=sys.stderr); rc = 1
    return rc

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