#!/usr/bin/env python3
# summary: Find and restore earlier versions of a file.
"""Earlier versions of one file, from local snapshots and your backup drive.

usage: starchaser versions show [FILE] | list FILE | restore VERSION FILE replace|both
VERSION is local:TIMESTAMP or backup:SNAPSHOT. Restores keep the current copy.
"""
import argparse
import json
import os
os.environ["QS_DISABLE_CRASH_HANDLER"] = "1"
os.environ["STARCHASER_QML_APP"] = "versions"
import re
import shutil
import subprocess
import sys
import tempfile
import time
import uuid
from pathlib import Path

HOME = Path.home()
VERSIONS = Path('/home/.starchaser-versions')


def checked_path(root, relative):
    parts = Path(relative).parts
    if not parts or any(p in ('..', '/') for p in parts):
        raise ValueError('Choose a file in your Home folder.')
    path = root
    for part in parts:
        path = path / part
        if path.is_symlink():
            raise ValueError("Earlier versions can't replace a link. Choose the original file instead.")
    return path


def relative_file(value):
    path = Path(value)
    if not path.is_absolute():
        path = HOME / path
    try:
        rel = path.relative_to(HOME)
    except ValueError:
        raise ValueError('Choose a file in your Home folder.') from None
    checked_path(HOME, rel)
    return str(rel)


def local_versions(relative):
    rows = []
    if VERSIONS.is_dir() and not VERSIONS.is_symlink():
        for snapshot in VERSIONS.iterdir():
            if not snapshot.name.isdigit() or snapshot.is_symlink():
                continue
            try:
                path = checked_path(VERSIONS, snapshot.name + '/' + HOME.name + '/' + relative)
                if path.is_file():
                    rows.append({'id': 'local:' + snapshot.name, 'time': int(snapshot.name), 'source': 'On this computer',
                                 'text': time.strftime('%b %d at %I:%M %p', time.localtime(int(snapshot.name)))})
            except (OSError, ValueError):
                continue
    return rows


def versions(relative):
    rows, warning = local_versions(relative), ''
    try:
        result = subprocess.run(['starchaser', 'backup', 'snapshots'], capture_output=True, text=True, timeout=120)
        data = json.loads(result.stdout)
        if not data.get('ok'):
            warning = data.get('errors', 'Connect your backup drive for more versions.')
        else:
            parent = str(Path(relative).parent)
            for snap in data.get('snapshots', [])[:100]:
                result = subprocess.run(['starchaser', 'backup', 'files', snap['id'], '' if parent == '.' else parent], capture_output=True, text=True, timeout=120)
                listing = json.loads(result.stdout)
                if any(n.get('path') == relative for n in listing.get('files', [])):
                    rows.append({'id': 'backup:' + snap['id'], 'time': snap['time'], 'text': snap['text'], 'source': 'Backup'})
    except (OSError, ValueError, subprocess.TimeoutExpired):
        warning = 'Connect your backup drive for more versions.'
    return {'ok': True, 'versions': sorted(rows, key=lambda r: r['time'], reverse=True), 'warning': warning}


def keep_current(target, saved):
    with saved.open('xb') as out, target.open('rb') as source:
        os.fchmod(out.fileno(), target.stat().st_mode & 0o777)
        shutil.copyfileobj(source, out)
        out.flush()
        os.fsync(out.fileno())


def restore_local(timestamp, relative, mode):
    if not re.fullmatch(r'[0-9]{1,12}', timestamp) or mode not in ('replace', 'both'):
        raise ValueError('Choose a version and whether to replace or keep both.')
    source = checked_path(VERSIONS, timestamp + '/' + HOME.name + '/' + relative)
    target = checked_path(HOME, relative)
    if not source.is_file():
        raise ValueError('That local version is no longer available. Look at the list again.')
    if not target.parent.is_dir():
        raise ValueError('The original folder is missing. Restore its folder from Backups first.')
    kept = ''
    if mode == 'both':
        target = target.with_name(target.stem + ' (earlier ' + timestamp + '-' + uuid.uuid4().hex[:6] + ')' + target.suffix)
    elif target.exists():
        if not target.is_file():
            raise ValueError("The current path isn't a regular file. Nothing was replaced.")
        saved = target.with_name(target.name + '.before-restore-' + uuid.uuid4().hex[:8])
        keep_current(target, saved)
        kept = str(saved)
    fd, temp = tempfile.mkstemp(prefix='.earlier-version-', dir=target.parent)
    try:
        with os.fdopen(fd, 'wb') as out, source.open('rb') as stream:
            shutil.copyfileobj(stream, out)
            os.fchmod(out.fileno(), os.fstat(stream.fileno()).st_mode & 0o777)
            out.flush()
            os.fsync(out.fileno())
        os.replace(temp, target)
    finally:
        Path(temp).unlink(missing_ok=True)
    return {'ok': True, 'path': str(target), 'kept': kept,
            'message': 'The earlier version was restored.' + (' Your current copy was kept as ' + Path(kept).name + '.' if kept else '')}


def main():
    parser = argparse.ArgumentParser(prog="starchaser versions", description=__doc__)
    subs = parser.add_subparsers(dest='command', required=True)
    for name in ('show', 'list'):
        subs.add_parser(name).add_argument('file', nargs='?' if name == 'show' else None)
    restore = subs.add_parser('restore')
    restore.add_argument('version'); restore.add_argument('file'); restore.add_argument('mode', choices=['replace', 'both'])
    args = parser.parse_args()
    try:
        relative = (args.file or '') if args.command == 'show' else relative_file(args.file)
        if args.command == 'show':
            env = dict(os.environ, STARCHASER_VERSION_FILE=relative)
            path = HOME / '.config/quickshell/versions'
            if not (path / 'shell.qml').is_file():
                path = Path(__file__).resolve().parents[1] / 'config/quickshell/versions'
            subprocess.Popen(['qs', '-p', str(path)], env=env, start_new_session=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
            return 0
        if args.command == 'list':
            result = versions(relative)
        elif args.version.startswith('local:'):
            result = restore_local(args.version[6:], relative, args.mode)
        elif args.version.startswith('backup:') and re.fullmatch(r'[a-f0-9]{8,64}', args.version[7:]):
            # Keep a current file before an explicit in-place restore, just as local versions do.
            target = checked_path(HOME, relative)
            if args.mode == 'replace' and target.is_file():
                saved = target.with_name(target.name + '.before-restore-' + uuid.uuid4().hex[:8])
                keep_current(target, saved)
            result = subprocess.run(['starchaser', 'backup', 'restore-start', args.version[7:], 'home', '--mode', args.mode, relative], capture_output=True, text=True)
            print(result.stdout, end='')
            return result.returncode
        else:
            raise ValueError('Choose a version from the list.')
        print(json.dumps(result))
        return 0
    except (ValueError, OSError) as error:
        print(json.dumps({'ok': False, 'errors': str(error)}))
        return 1


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