#!/usr/bin/env python3
# summary: Reset an account password from recovery media.
"""Reset a computer account from the Starchaser USB stick.

Run with sudo -n for administrator permission without a password prompt.
It fails if sudo needs a password; -n does not grant permission by itself.
With no command, in a terminal, it runs a step-by-step guide.
The unlock and set commands read a disk key or new password from standard
input, one line at a time, never from command arguments.
"""
import argparse
import fcntl
import getpass
import io
import json
import os
import re
import signal
import stat
import subprocess
import sys
import tempfile
from pathlib import Path

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

safe_streams()

REPO = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(REPO / "system/usr/local/lib/starchaser"))
sys.path.append("/usr/local/lib/starchaser")
import account_tools as account

BASE = Path("/run/starchaser-reset")
DEVICE = re.compile(r"^/dev/(?:[A-Za-z0-9_+.-]+/)*[A-Za-z0-9_+.-]+$")
DISK_HINT = "Without the disk key, nobody can reach the files on this drive, not even Starchaser"


def command(args, secret=None):
    return subprocess.run(args, input=secret, capture_output=True, text=True, check=False)


def devices():
    result = command(["lsblk", "--json", "--tree", "--bytes", "--paths", "--output", "PATH,TYPE,FSTYPE,SIZE,LABEL,MOUNTPOINTS,UUID,PARTUUID"])
    if result.returncode:
        raise ValueError("The computer's drives couldn't be read.")
    return json.loads(result.stdout).get("blockdevices", [])


def flatten(nodes):
    for node in nodes:
        yield node
        yield from flatten(node.get("children", []))


def mounted_live(node):
    return any(p and not (p == str(BASE) or p.startswith(str(BASE) + "/")) for p in node.get("mountpoints", []) or [])


def available(nodes):
    # Excluding a disk with a live mount also excludes the USB's other partitions and its backing devices.
    try:
        boot_args = dict(word.split("=", 1) for word in Path("/proc/cmdline").read_text().split() if "=" in word)
    except OSError:
        boot_args = {}

    def boot_device(node):
        # A USB copied into memory can be unmounted already, but its boot identity still excludes the whole disk.
        return any(boot_args.get(arg) and str(node.get(field, "")).lower() == boot_args[arg].lower()
                   for arg, field in (("archisosearchuuid", "uuid"), ("archisolabel", "label"), ("archisodevice", "path")))

    for node in nodes:
        family = list(flatten([node]))
        if any(mounted_live(n) or boot_device(n) for n in family):
            continue
        yield from family


def validate_device(path, nodes=None):
    if not DEVICE.fullmatch(path) or any(p in (".", "..") for p in Path(path).parts):
        raise ValueError("Pick a drive from the list.")
    nodes = devices() if nodes is None else nodes
    node = next((n for n in available(nodes) if n.get("path") == path), None)
    if node is None or not stat.S_ISBLK(os.stat(path).st_mode):
        raise ValueError("That drive is unavailable or is being used by the live system.")
    return node


class DiskKeyError(ValueError):
    """An encrypted drive was checked, but its key did not unlock it."""


class Session:
    def __init__(self):
        BASE.mkdir(mode=0o700, parents=True, exist_ok=True)
        if BASE.is_symlink() or BASE.stat().st_uid != 0 or BASE.stat().st_mode & 0o077:
            raise ValueError("The recovery work folder isn't private. Restart the USB stick and try again.")
        self.lock = (BASE / "lock").open("a")
        fcntl.flock(self.lock, fcntl.LOCK_EX)
        self.state_path = BASE / "session.json"
        self.state = json.loads(self.state_path.read_text()) if self.state_path.exists() else {"mounts": [], "mappers": []}

    def save(self):
        temp = BASE / (".session." + str(os.getpid()) + ".tmp")
        with temp.open("w") as stream:
            json.dump(self.state, stream)
            stream.flush()
            os.fsync(stream.fileno())
        temp.replace(self.state_path)

    def mount(self, dev, target, fs, readonly=False, subvol=None, subvolid=None):
        target = Path(target)
        target.mkdir(mode=0o700, parents=True, exist_ok=True)
        if target.is_symlink() or command(["findmnt", "--noheadings", "--mountpoint", str(target)]).returncode == 0:
            raise ValueError("That recovery folder is already in use. Choose Back and try again.")
        opts = ["ro" if readonly else "rw", "nosuid", "nodev", "noexec"]
        if readonly:
            if fs == "btrfs":
                opts.append("rescue=nologreplay")
            elif fs in ("ext3", "ext4"):
                opts.append("noload")
            elif fs == "xfs":
                opts.append("norecovery")
        if subvol:
            opts.append("subvol=" + subvol)
        if subvolid is not None:
            if not re.fullmatch(r'[0-9]+', str(subvolid)):
                raise ValueError("The recorded Home subvolume couldn't be checked. Nothing was changed.")
            opts.append("subvolid=" + str(subvolid))
        entry = {"path": str(target), "device": dev}
        # Record ownership first so an interrupted mount can still be closed by the next done command.
        self.state["mounts"].append(entry)
        self.save()
        result = command(["mount", "-o", ",".join(opts), dev, str(target)])
        if result.returncode:
            self.state["mounts"].remove(entry)
            self.save()
            return False
        return True

    def mount_system(self, dev, target, node, readonly=False):
        fs = node.get("fstype")
        if fs == "btrfs" and self.mount(dev, target, fs, readonly, "@"):
            return True
        return self.mount(dev, target, fs, readonly)

    def unmount(self, entry):
        path = entry["path"]
        allowed = path in (str(BASE / "root"), str(BASE / "root/home")) or re.fullmatch(re.escape(str(BASE)) + r"/probe-[A-Za-z0-9_-]+", path)
        if not allowed:
            raise ValueError("Recovery found an unfamiliar folder and left it alone.")
        result = command(["findmnt", "--noheadings", "--raw", "--mountpoint", path, "--output", "SOURCE"])
        if result.returncode == 0:
            source = result.stdout.strip().split("[")[0]
            if os.path.realpath(source) != os.path.realpath(entry["device"]):
                raise ValueError("Recovery found a drive it didn't mount and left it alone.")
            if command(["umount", path]).returncode:
                raise ValueError("The drive is still in use. Close other recovery windows and try again.")
        self.state["mounts"].remove(entry)
        self.save()

    def done(self):
        os.sync()
        errors = []
        for entry in list(reversed(self.state["mounts"])):
            try:
                self.unmount(entry)
            except ValueError as error:
                errors.append(str(error))
        for name in list(reversed(self.state["mappers"])):
            if not re.fullmatch(r"starchaser-reset-[0-9]+", name):
                errors.append("Recovery found a drive it did not open and left it alone.")
                continue
            if Path("/dev/mapper", name).exists() and command(["cryptsetup", "close", name]).returncode:
                errors.append("The unlocked drive is still in use. Choose Back and try again.")
                continue
            self.state["mappers"].remove(name)
            self.save()
        self.state.pop("device", None)
        self.save()
        if errors:
            raise ValueError(" ".join(errors))

    def drives(self):
        result = []
        for node in available(devices()):
            dev = node.get("path", "")
            if node.get("type") not in ("part", "crypt", "lvm") or not node.get("fstype"):
                continue
            validate_device(dev)
            info = {"device": dev, "size": node.get("size", 0), "label": node.get("label") or "",
                    "encrypted": node["fstype"] == "crypto_LUKS", "locked": node["fstype"] == "crypto_LUKS"}
            if info["locked"]:
                if not node.get("children"):
                    result.append(info)
                continue
            target = Path(tempfile.mkdtemp(prefix="probe-", dir=BASE))
            try:
                if not self.mount_system(dev, target, node, True):
                    continue
                if (target / "etc/shadow").is_file() and (target / "etc/os-release").is_file():
                    hostname = target / "etc/hostname"
                    info.update({"computer": hostname.read_text().strip() if hostname.exists() else "Computer",
                                 "accounts": len(account.accounts(target))})
                    result.append(info)
            finally:
                for entry in list(reversed(self.state["mounts"])):
                    if entry["path"] == str(target):
                        self.unmount(entry)
                target.rmdir()
        return {"drives": result}

    def unlock(self, dev, key):
        node = validate_device(dev)
        if node.get("fstype") != "crypto_LUKS":
            raise ValueError("That drive doesn't need a disk key.")
        taken = {n.get("path") for n in flatten(devices())}
        number = 0
        while f"/dev/mapper/starchaser-reset-{number}" in taken or Path(f"/dev/mapper/starchaser-reset-{number}").exists():
            number += 1
        name = f"starchaser-reset-{number}"
        self.state["mappers"].append(name)
        self.save()
        result = command(["cryptsetup", "open", "--key-file=-", dev, name], key)
        if result.returncode:
            if not Path("/dev/mapper", name).exists():
                self.state["mappers"].remove(name)
                self.save()
            raise DiskKeyError("That disk key didn't work. Check it and try again.")
        return {"device": "/dev/mapper/" + name, "hint": DISK_HINT}

    def accounts(self, dev):
        node = validate_device(dev)
        if self.state["mounts"]:
            raise ValueError("Choose Back before opening another drive.")
        target = BASE / "root"
        if not self.mount_system(dev, target, node):
            raise ValueError("That computer's files couldn't be opened.")
        if not (target / "etc/shadow").is_file() or not (target / "etc/os-release").is_file():
            raise ValueError("No installed system was found on that drive.")
        self.state["device"] = dev
        self.save()
        # A separate home holds saved passwords. Failure to open it must not block a password reset.
        home = target / "home"
        if home.is_dir() and not home.is_symlink():
            opened = node.get("fstype") == "btrfs" and self.mount(dev, home, "btrfs", subvol="@home")
            fstab = target / "etc/fstab"
            if not opened and fstab.exists():
                for line in fstab.read_text().splitlines():
                    fields = line.split()
                    if len(fields) < 3 or fields[0].startswith("#") or fields[1] != "/home":
                        continue
                    source = fields[0]
                    for candidate in available(devices()):
                        path = candidate.get("path", "")
                        if source not in (path, "UUID=" + str(candidate.get("uuid")), "PARTUUID=" + str(candidate.get("partuuid"))):
                            continue
                        validate_device(path)
                        subvol = next((o.split("=", 1)[1] for o in (fields[3].split(",") if len(fields) > 3 else []) if o.startswith("subvol=")), None)
                        if subvol and (candidate.get("fstype") != "btrfs" or not re.fullmatch(r"[A-Za-z0-9_@.-]+", subvol)):
                            subvol = None
                        self.mount(path, home, candidate.get("fstype"), subvol=subvol)
        return {"users": account.accounts(target)}

    def set_password(self, name, password, reset=False, root_dir=None):
        target = Path(root_dir) if root_dir else BASE / "root"
        if not root_dir:
            if not self.state.get("device") or not any(e["path"] == str(target) for e in self.state["mounts"]):
                raise ValueError("Choose a drive and an account first.")
            mounted = command(["findmnt", "--noheadings", "--raw", "--mountpoint", str(target), "--output", "SOURCE"])
            if mounted.returncode or os.path.realpath(mounted.stdout.strip().split("[")[0]) != os.path.realpath(self.state["device"]):
                raise ValueError("The chosen drive is no longer open. Choose it again.")
        user = account.find_account(name, target)
        account.write_password(target, name, password)
        keyring = account.reset_keyring(target, user) if reset else {"reset": False, "note": account.KEYRING_NOTE}
        return {"name": name, "keyring": keyring}


def parser():
    result = CommandParser(description=__doc__)
    commands = result.add_subparsers(dest="verb", metavar="command")
    commands.add_parser("drives", help="list available drives for password recovery")
    unlock = commands.add_parser("unlock", help="open an encrypted drive using its disk key",
                                 description="Read the disk key from standard input and open the encrypted drive.")
    unlock.add_argument("device", help="drive path from drives, such as /dev/sda2")
    accounts = commands.add_parser("accounts", help="open a drive and list its accounts")
    accounts.add_argument("device", nargs="?", help="drive path from drives or unlock (required for recovery)")
    accounts.add_argument("--root-dir", help=argparse.SUPPRESS)
    setter = commands.add_parser("set", help="set a new password for an account on the opened drive",
                                 description="Run accounts first, then supply the new password as one line on standard input.")
    setter.add_argument("user", help="account name from accounts")
    setter.add_argument("--reset-keyring", action="store_true", help="also set aside the account's saved passwords so apps can save new ones; old saved passwords stay in a backup")
    setter.add_argument("--root-dir", help=argparse.SUPPRESS)
    commands.add_parser("done", help="unmount recovery drives and lock any drives opened by unlock")
    return result


def interactive(session):
    try:
        print("Reset a forgotten password. Your files will be kept.")
        drives = session.drives()["drives"]
        if not drives:
            print("No Starchaser computer was found on this computer's drives.")
            return
        for index, drive in enumerate(drives, 1):
            print(f"{index}. {drive.get('computer') or drive.get('label') or 'Computer'}" + (" — Locked: needs your disk key" if drive["locked"] else ""))
        try:
            selected = int(input("Drive number: ")) - 1
        except ValueError:
            raise ValueError("Pick a drive number from the list.") from None
        if not 0 <= selected < len(drives):
            raise ValueError("Pick a drive from the list.")
        drive = drives[selected]
        dev = drive["device"]
        if drive["locked"]:
            print(DISK_HINT)
            dev = session.unlock(dev, account.password_line(io.StringIO(getpass.getpass("Disk key: "))))["device"]
        users = session.accounts(dev)["users"]
        for user in users:
            print(f"{user['name']} — {user['full']}")
        name = input("Account name: ")
        account.find_account(name, BASE / "root")
        password = account.password_line(io.StringIO(getpass.getpass("New password: ")))
        if password != getpass.getpass("New password again: "):
            raise ValueError("The passwords don't match. Try again.")
        print(account.KEYRING_NOTE)
        reset = input("Also reset saved passwords? [y/N] ").lower() == "y"
        result = session.set_password(name, password, reset)
        print(f"Password changed for {name}.")
        print(result["keyring"]["note"])
    finally:
        session.done()


def main(argv=None):
    args = parser().parse_args(argv)
    session = None
    handlers = {}
    try:
        if not args.verb and not sys.stdin.isatty():
            raise ValueError("Run starchaser reset password with no arguments in a terminal for a step-by-step guide, or use one of: drives, unlock, accounts, set, done.")
        # Fake roots bypass disk state and root checks so the same account rules can be tested without privileges.
        if getattr(args, "root_dir", None):
            target = Path(args.root_dir).resolve()
            if args.verb == "accounts":
                result = {"users": account.accounts(target)}
            else:
                user = account.find_account(args.user, target)
                account.write_password(target, user["name"], account.password_line(sys.stdin))
                result = {"name": user["name"], "keyring": account.reset_keyring(target, user) if args.reset_keyring else {"reset": False, "note": account.KEYRING_NOTE}}
        else:
            if os.geteuid() != 0:
                raise ValueError("Start the computer from the Starchaser USB stick. Open a terminal there and run: sudo starchaser reset password drives")
            session = Session()
            def interrupted(signum, frame):
                raise KeyboardInterrupt
            for signum in (signal.SIGTERM, signal.SIGHUP):
                handlers[signum] = signal.signal(signum, interrupted)
            if not args.verb:
                interactive(session)
                return 0
            if args.verb == "drives":
                result = session.drives()
            elif args.verb == "unlock":
                result = session.unlock(args.device, account.password_line(sys.stdin))
            elif args.verb == "accounts":
                if not args.device:
                    raise ValueError("Pick a drive from the list.")
                result = session.accounts(args.device)
            elif args.verb == "set":
                result = session.set_password(args.user, account.password_line(sys.stdin), args.reset_keyring)
            else:
                session.done()
                result = {}
        print(json.dumps({"ok": True, **result}))
        return 0
    except (OSError, ValueError, KeyError, EOFError, KeyboardInterrupt):
        error = sys.exc_info()[1]
        message = str(error) if isinstance(error, ValueError) and not isinstance(error, json.JSONDecodeError) else "Recovery couldn't finish. Choose Back and try again."
        # a refused password or a wrong disk key leaves the chosen drive open, so the person can fix the box and try again
        if session is not None and args.verb in (None, "drives", "accounts", "done"):
            try:
                session.done()
            except (OSError, ValueError):
                message += " The drive could not be closed. Run the done command before removing it."
        result = {"ok": False, "errors": message}
        if isinstance(error, DiskKeyError):
            result["hint"] = DISK_HINT
        print(json.dumps(result))
        return 1
    finally:
        if session is not None:
            session.lock.close()
        for signum, handler in handlers.items():
            signal.signal(signum, handler)


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