#!/usr/bin/env python3
# summary: Run pending account or system migrations, with backups.
"""Run numbered migrations in order. A failed step stops the queue and stays pending.
--pending lists unfinished steps without writing anything.
--mark-current records today's steps without running them, for a completed fresh setup.
System migrations require root; user migrations run as the desktop account.
User file changes appear in starchaser defaults last and can be undone there.
System files and their migration records return together with Settings > Recovery.
"""
# Separate root/account state adapts the run-once idea from Omarchy (MIT),
# https://github.com/basecamp/omarchy/blob/748fa3c0d/bin/omarchy-migrate. No code copied.
import argparse
import fcntl
import hashlib
import importlib.machinery
import importlib.util
import json
import os
from pathlib import Path
import re
import shutil
import subprocess
import sys
import time
import uuid

sys.path.insert(0, str(Path(__file__).resolve().parent))
from starchaser_cli import CommandParser

ROOT = Path(__file__).resolve().parents[1]
NAME = re.compile(r"[0-9]{4}-[a-z0-9]+(?:-[a-z0-9]+)*\.sh")


def defaults_module():
    loader = importlib.machinery.SourceFileLoader("starchaser_migration_journal", str(ROOT / "bin/starchaser-defaults"))
    spec = importlib.util.spec_from_loader(loader.name, loader)
    module = importlib.util.module_from_spec(spec)
    loader.exec_module(module)
    return module


class MigrationRunner:
    def __init__(self, root, scope, state, defaults):
        self.root, self.scope, self.state, self.defaults = Path(root), scope, Path(state), defaults
        self.base = Path("/") if scope == "system" else Path.home()

    def scripts(self):
        folder = self.root / "migrations" / self.scope
        if not folder.is_dir():
            raise ValueError(f"Migration folder is missing: {folder}")
        scripts = sorted(folder.glob("*.sh"))
        numbers = set()
        for script in scripts:
            if not NAME.fullmatch(script.name) or script.name[:4] in numbers or script.is_symlink():
                raise ValueError(f"Invalid or repeated migration number: {script.name}")
            numbers.add(script.name[:4])
        return scripts

    def pending(self):
        return [p for p in self.scripts() if not (self.state / p.name).is_file()]

    def backup_paths(self, script):
        paths = []
        for line in script.read_text().splitlines():
            if not line.startswith("# backup:"):
                continue
            # Paths are relative to / for system work and HOME for account work.
            rel = Path(line.removeprefix("# backup:").strip())
            if rel.is_absolute() or ".." in rel.parts or not rel.parts:
                raise ValueError(f"Invalid backup path in {script.name}: {rel}")
            path = self.base / rel
            if self.scope == "user" and self.defaults.never(path):
                raise ValueError("Migrations can't change your personal user.lua")
            for parent in [path, *path.parents]:
                if parent == self.base:
                    break
                if parent.is_symlink():
                    raise ValueError(f"Can't back up a link: {parent}")
            paths.append(path)
        return list(dict.fromkeys(paths))

    def prepare(self, script):
        d = self.defaults
        active = self.state / ("." + script.name + ".running")
        if active.exists():
            # Power loss: retain the original backup, then rerun the idempotent script.
            tx = d.MIGRATIONS / active.read_text().strip()
            journal = json.loads((tx / "journal.json").read_text())
            if journal.get("status") == "failed" or (journal.get("status") == "undone" and journal.get("returncode")):
                # Automatic failure rollback also says "undone". Finish that
                # recovery, then retry with a new journal of the restored files.
                if journal["status"] == "failed":
                    d.put_back(tx, journal)
                active.unlink()
            else:
                return tx, journal, active
        tx, journal = d.new_transaction()
        tx = tx.with_name(tx.name + "-" + script.stem + "-" + uuid.uuid4().hex[:8])
        journal.update(id=tx.name, migration=script.name, scope=self.scope)
        (tx / "files").mkdir(parents=True, mode=0o700)
        os.chmod(tx, 0o700)
        for path in self.backup_paths(script):
            if path.exists() and (not path.is_file() or path.stat().st_nlink != 1):
                raise ValueError(f"Can't back up this file: {path}")
            e = {"path": str(path), "group": "numbered-migrations", "state": "backed-up"}
            if path.exists():
                st = path.stat()
                backup = Path("files") / path.relative_to(self.base)
                (tx / backup).parent.mkdir(parents=True, exist_ok=True)
                shutil.copy2(path, tx / backup)
                e.update(action="replace", backup=str(backup),
                         before={"mode": st.st_mode & 0o777, "mtime_ns": st.st_mtime_ns,
                                 "inode": st.st_ino, "size": st.st_size,
                                 "sha256": d.sha256(path), "uid": st.st_uid, "gid": st.st_gid})
            else:
                e.update(action="create", before={"state": "absent"})
            journal["entries"].append(e)
        d.write_json(tx / "journal.json", journal)
        d.write_atomic(active, (tx.name + "\n").encode(), 0o600)
        return tx, journal, active

    def execute(self, script):
        d = self.defaults
        for line in script.read_text().splitlines():
            if line.startswith("# if-missing:"):
                rel = Path(line.removeprefix("# if-missing:").strip())
                if rel.is_absolute() or ".." in rel.parts:
                    raise ValueError(f"Invalid conditional path in {script.name}")
                if os.path.lexists(self.base / rel) and not (self.state / ("." + script.name + ".running")).exists():
                    d.write_json(self.state / script.name, {"result": "personal-copy-kept"})
                    return 0
        tx, journal, active = self.prepare(script)
        if journal.get("status") == "undone":
            # Undo can finish before the interrupted run writes its done marker.
            # Acknowledge that choice durably before discarding the resume record.
            self.complete(script, tx, active, "undone")
            return 0
        env = dict(os.environ, STARCHASER_MIGRATION_ROOT=str(self.root), PYTHONDONTWRITEBYTECODE="1")
        result = subprocess.run(["bash", "-euo", "pipefail", str(script)], env=env)
        changed = []
        for e in journal["entries"]:
            # A resumed journal describes the last attempt's result. Compare with
            # the original backup again, whether this attempt deletes or replaces it.
            if e["action"] == "remove":
                e["action"] = "replace"
            path = Path(e["path"])
            if path.is_file() and not path.is_symlink():
                after = d.sha256(path)
                st = path.stat()
                if e["action"] == "replace" and after == e["before"]["sha256"] and \
                        st.st_mode & 0o777 == e["before"]["mode"] and \
                        (st.st_uid, st.st_gid) == (e["before"]["uid"], e["before"]["gid"]):
                    continue
                e.update(after=after, state="done")
                changed.append(e)
            elif not path.exists() and e["action"] == "replace":
                e.update(action="remove", state="done")
                changed.append(e)
        journal["entries"] = changed
        journal.update(status="done" if result.returncode == 0 else "failed",
                       finished=time.strftime("%Y-%m-%dT%H:%M:%S"), returncode=result.returncode)
        d.write_json(tx / "journal.json", journal)
        if result.returncode:
            d.put_back(tx, journal)
            active.unlink()
            print(f"Migration {script.name} did not finish. Its files were restored; it will retry at the next update or sign-in.", file=sys.stderr)
            return 1
        if not changed:
            # Runtime-only or already-applied work must not hide the last useful Undo.
            journal["status"] = "nothing"
            d.write_json(tx / "journal.json", journal)
        else:
            d.set_marker(tx.name, ["numbered-migrations"])
        self.complete(script, tx, active, "done")
        return 0

    def complete(self, script, tx, active, result):
        self.defaults.write_json(self.state / script.name,
                                 {"sha256": hashlib.sha256(script.read_bytes()).hexdigest(),
                                  "journal": str(tx), "result": result})
        active.unlink()

    def run(self, mark_current=False):
        # Validate before creating any state; serialize both migrations and defaults Undo.
        self.scripts()
        self.state.mkdir(parents=True, exist_ok=True, mode=0o700)
        with (self.state / ".lock").open("a") as lock:
            fcntl.flock(lock, fcntl.LOCK_EX)
            own = self.defaults.lock(self.defaults.MIGRATIONS / ".lock", 5)
            if not own:
                print("A desktop settings move is running. Migrations will retry later.", file=sys.stderr)
                return 1
            try:
                for script in self.pending():
                    if mark_current:
                        if (self.state / ("." + script.name + ".running")).exists():
                            raise ValueError(f"Finish the interrupted migration before marking it current: {script.name}")
                        self.defaults.write_json(self.state / script.name, {"result": "fresh-install"})
                    else:
                        print(f"Updating Starchaser: {script.stem[5:].replace('-', ' ')}", flush=True)
                        if self.execute(script):
                            return 1
                return 0
            finally:
                own.close()


def main(argv=None):
    parser = CommandParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument("scope", choices=("system", "user"))
    mode = parser.add_mutually_exclusive_group()
    mode.add_argument("--pending", action="store_true", help="list unfinished migrations without changes")
    mode.add_argument("--mark-current", action="store_true", help="record completed fresh setup without running old work")
    args = parser.parse_args(argv)
    if (args.scope == "system") != (os.geteuid() == 0):
        parser.error("run system migrations as root: run it with sudo" if args.scope == "system"
                     else "run user migrations as your own account, without sudo")
    d = defaults_module()
    state = Path(os.environ.get("XDG_STATE_HOME") or Path.home() / ".local/state") / "starchaser/migrations-done"
    if args.scope == "system":
        state = Path("/var/lib/starchaser/migrations")
        d.STATE = Path("/var/lib/starchaser")
        d.MIGRATIONS = d.STATE / "migration-backups"
        d.MARKER = d.STATE / "migration-files.json"
    runner = MigrationRunner(ROOT, args.scope, state, d)
    if args.pending:
        pending = runner.pending()
        for script in pending:
            print(script.name)
        if not pending:
            print("Nothing is pending.", file=sys.stderr)
        return 0
    return runner.run(mark_current=args.mark_current)


if __name__ == "__main__":
    try:
        sys.exit(main())
    except (OSError, ValueError, subprocess.SubprocessError) as exc:
        print(f"starchaser migrate: {exc}. Pending work will retry; no later migrations ran.", file=sys.stderr)
        sys.exit(1)
