#!/usr/bin/env qore

# qtar - command-line interface for Qore TAR archive operations
#
# Copyright (C) 2026 Qore Technologies, s.r.o.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.

%modern

%requires tar
%requires Util

%exec-class QTarApp

class QTarApp {
    public {
        const Version = "1.0.0";

        const CompressionExtMap = {
            ".tar.gz": TAR_CM_GZIP,
            ".tgz": TAR_CM_GZIP,
            ".tar.bz2": TAR_CM_BZIP2,
            ".tbz2": TAR_CM_BZIP2,
            ".tar.xz": TAR_CM_XZ,
            ".txz": TAR_CM_XZ,
            ".tar.zst": TAR_CM_ZSTD,
            ".tar.lz4": TAR_CM_LZ4,
        };

        const FormatMap = {
            "pax": TAR_FORMAT_PAX,
            "ustar": TAR_FORMAT_USTAR,
            "gnu": TAR_FORMAT_GNU,
            "v7": TAR_FORMAT_V7,
        };

        const CreateOpts = {
            "gzip": "z,gzip",
            "bzip2": "j,bzip2",
            "xz": "J,xz",
            "zstd": "zstd",
            "lz4": "lz4",
            "level": "l,level=i",
            "format": "f,format=s",
            "dereference": "L,dereference",
            "directory": "C,directory=s",
            "verbose": "v,verbose",
            "help": "h,help",
        };

        const ExtractOpts = {
            "directory": "C,directory=s",
            "include": "include=s@",
            "exclude": "exclude=s@",
            "strip": "strip=i",
            "no_preserve": "no-preserve",
            "overwrite": "o,overwrite",
            "no_overwrite": "no-overwrite",
            "verbose": "v,verbose",
            "help": "h,help",
        };

        const ListOpts = {
            "long": "l,long",
            "verbose": "v,verbose",
            "help": "h,help",
        };

        const AddOpts = {
            "dereference": "L,dereference",
            "directory": "C,directory=s",
            "verbose": "v,verbose",
            "help": "h,help",
        };

        const EncryptOpts = {
            "key": "k,key=s",
            "key_file": "K,key-file=s",
            "password": "p,password=s",
            "gen_key": "gen-key",
            "help": "h,help",
        };

        const DecryptOpts = {
            "key": "k,key=s",
            "key_file": "K,key-file=s",
            "password": "p,password=s",
            "help": "h,help",
        };

        const KeySize = 32;
        const IVSize = 16;
        const SaltSize = 16;
        const Cipher = "aes-256-cbc";
        const PasswordMagic = <54454E43>;  # "TENC"
    }

    private {
        TerminalColor tc();
    }

    constructor() {
        if (!ARGV) {
            usage();
            exit(1);
        }

        string cmd = shift ARGV;

        try {
            switch (cmd) {
                case "create": case "c":
                    cmdCreate();
                    break;
                case "extract": case "x":
                    cmdExtract();
                    break;
                case "list": case "t":
                    cmdList();
                    break;
                case "add": case "a":
                    cmdAdd();
                    break;
                case "info": case "i":
                    cmdInfo();
                    break;
                case "encrypt": case "e":
                    cmdEncrypt();
                    break;
                case "decrypt": case "d":
                    cmdDecrypt();
                    break;
                case "cat":
                    cmdCat();
                    break;
                case "verify":
                    cmdVerify();
                    break;
                case "diff":
                    cmdDiff();
                    break;
                case "--help": case "-h": case "help":
                    usage();
                    break;
                case "--version": case "-V":
                    printf("qtar %s\n", Version);
                    break;
                default:
                    stderr.printf("%s unknown command: %s\n", tc.error("error:"), cmd);
                    stderr.printf("Run %s for available commands\n", tc.bold("qtar --help"));
                    exit(1);
            }
        } catch (hash<ExceptionInfo> ex) {
            stderr.printf("%s %s: %s\n", tc.error("error:"), ex.err, ex.desc);
            exit(1);
        }
    }

    # --- Create command ---
    private cmdCreate() {
        hash<auto> opts = (new GetOpt(CreateOpts)).parse3(\ARGV);
        if (opts.help) {
            usageCreate();
            return;
        }

        if (ARGV.size() < 2) {
            stderr.printf("%s create requires <archive> <files/dirs...>\n", tc.error("error:"));
            usageCreate();
            exit(1);
        }

        string archive_path = shift ARGV;
        int cm = getCompressionFromOpts(opts, archive_path);
        int fmt = opts.format ? (FormatMap{opts.format} ?? TAR_FORMAT_PAX) : TAR_FORMAT_PAX;

        hash<TarCreateOptions> create_opts = <TarCreateOptions>{
            "compression_method": cm,
            "format": fmt,
        };
        if (exists opts.level) {
            create_opts.compression_level = opts.level;
        }

        TarFile tar(archive_path, "w", create_opts);
        int count = 0;

        *string base_dir = opts.directory;
        bool verbose = opts.verbose ?? False;

        # Pre-scan for total count if verbose (enables [N/Total] progress)
        int total = -1;
        if (verbose) {
            total = 0;
            foreach string path in (ARGV) {
                string full_path = base_dir ? base_dir + "/" + path : path;
                if (is_dir(full_path)) {
                    total += countEntries(full_path);
                } else if (is_file(full_path) || is_link(full_path)) {
                    ++total;
                }
            }
        }

        int progress = 0;

        foreach string path in (ARGV) {
            string full_path = base_dir ? base_dir + "/" + path : path;
            if (is_dir(full_path)) {
                count += walkDirectory(tar, full_path, path, opts.dereference ?? False,
                    verbose, NOTHING, \progress, total);
            } else if (is_file(full_path) || is_link(full_path)) {
                if (is_link(full_path) && !(opts.dereference ?? False)) {
                    tar.addSymlink(path, readlink(full_path));
                } else {
                    tar.addFile(path, full_path);
                }
                ++count;
                if (verbose) {
                    ++progress;
                    stderr.printf("[%d/%d] %s\n", progress, total, path);
                }
            } else {
                throw "TAR-ERROR", sprintf("path does not exist: %s", full_path);
            }
        }

        tar.close();

        stderr.printf("%s created %s (%s, %s, %s)\n",
            tc.success("ok:"),
            tc.bold(archive_path),
            tc.info(sprintf("%d entr%s", count, count == 1 ? "y" : "ies")),
            get_compression_name(cm),
            get_format_name(fmt),
        );
    }

    # --- Extract command ---
    private cmdExtract() {
        hash<auto> opts = (new GetOpt(ExtractOpts)).parse3(\ARGV);
        if (opts.help) {
            usageExtract();
            return;
        }

        if (!ARGV) {
            stderr.printf("%s extract requires <archive>\n", tc.error("error:"));
            exit(1);
        }

        string archive_path = shift ARGV;
        string destination = opts.directory ?? ".";

        hash<TarExtractOptions> extract_opts = <TarExtractOptions>{
            "destination": destination,
            "preserve_permissions": opts.no_preserve ? False : True,
            "preserve_times": True,
            "overwrite": opts.no_overwrite ? False : True,
            "create_directories": True,
        };
        if (opts.include) {
            extract_opts.include = opts.include;
        }
        if (opts.exclude) {
            extract_opts.exclude = opts.exclude;
        }
        if (opts.strip) {
            extract_opts.strip_count = opts.strip;
        }

        TarFile tar(archive_path, "r");
        list<string> extracted;
        if (opts.verbose) {
            extracted = tar.extractAll(extract_opts, sub (string name, int current, int total) {
                stderr.printf("[%d/%d] %s\n", current, total, name);
            });
        } else {
            extracted = tar.extractAll(extract_opts);
        }
        tar.close();

        stderr.printf("%s extracted %s from %s to %s\n",
            tc.success("ok:"),
            tc.info(sprintf("%d entr%s", extracted.size(),
                extracted.size() == 1 ? "y" : "ies")),
            tc.bold(archive_path),
            tc.bold(destination),
        );
    }

    # --- List command ---
    private cmdList() {
        hash<auto> opts = (new GetOpt(ListOpts)).parse3(\ARGV);
        if (opts.help) {
            usageList();
            return;
        }

        if (!ARGV) {
            stderr.printf("%s list requires <archive>\n", tc.error("error:"));
            exit(1);
        }

        string archive_path = shift ARGV;
        TarFile tar(archive_path, "r");
        list<hash<TarEntryInfo>> entries = tar.entries();
        tar.close();

        bool long_fmt = opts.long ?? opts.verbose ?? False;

        foreach hash<TarEntryInfo> entry in (entries) {
            if (long_fmt) {
                string type_char = entry.is_directory ? "d" : (entry.is_symlink ? "l" : "-");
                string mode_str = type_char + formatMode(entry.mode);
                string owner = (entry.uname ?? string(entry.uid)) + "/"
                    + (entry.gname ?? string(entry.gid));
                string date_str = entry.modified.format("YYYY-MM-DD HH:mm");
                string size_str = sprintf("%8d", entry.size);

                string name = entry.name;
                if (entry.is_symlink && entry.link_target) {
                    name += " -> " + entry.link_target;
                }

                printf("%s %s %s %s %s\n",
                    tc.dim(mode_str),
                    tc.cyan(sprintf("%-16s", owner)),
                    tc.number(size_str),
                    tc.dim(date_str),
                    entry.is_directory ? tc.blue(name) : name,
                );
            } else {
                if (entry.is_directory) {
                    printf("%s\n", tc.blue(entry.name));
                } else {
                    printf("%s\n", entry.name);
                }
            }
        }

        stderr.printf("%s %s in %s\n",
            tc.info("total:"),
            tc.bold(sprintf("%d entr%s", entries.size(), entries.size() == 1 ? "y" : "ies")),
            archive_path,
        );
    }

    # --- Add command ---
    private cmdAdd() {
        hash<auto> opts = (new GetOpt(AddOpts)).parse3(\ARGV);
        if (opts.help) {
            usageAdd();
            return;
        }

        if (ARGV.size() < 2) {
            stderr.printf("%s add requires <archive> <files/dirs...>\n", tc.error("error:"));
            exit(1);
        }

        string archive_path = shift ARGV;
        TarFile tar(archive_path, "a");
        int count = 0;

        *string base_dir = opts.directory;

        foreach string path in (ARGV) {
            string full_path = base_dir ? base_dir + "/" + path : path;
            if (is_dir(full_path)) {
                count += walkDirectory(tar, full_path, path, opts.dereference ?? False,
                    opts.verbose ?? False);
            } else if (is_file(full_path) || is_link(full_path)) {
                if (is_link(full_path) && !(opts.dereference ?? False)) {
                    tar.addSymlink(path, readlink(full_path));
                } else {
                    tar.addFile(path, full_path);
                }
                if (opts.verbose) {
                    printf("%s\n", path);
                }
                ++count;
            } else {
                throw "TAR-ERROR", sprintf("path does not exist: %s", full_path);
            }
        }

        tar.close();

        stderr.printf("%s added %s to %s\n",
            tc.success("ok:"),
            tc.info(sprintf("%d entr%s", count, count == 1 ? "y" : "ies")),
            tc.bold(archive_path),
        );
    }

    # --- Info command ---
    private cmdInfo() {
        if (ARGV.size() < 1 || ARGV[0] == "-h" || ARGV[0] == "--help") {
            usageInfo();
            if (!ARGV || ARGV[0] == "-h" || ARGV[0] == "--help") {
                return;
            }
        }

        string archive_path = shift ARGV;
        TarFile tar(archive_path, "r");
        list<hash<TarEntryInfo>> entries = tar.entries();

        int file_count = 0;
        int dir_count = 0;
        int symlink_count = 0;
        int total_size = 0;

        foreach hash<TarEntryInfo> entry in (entries) {
            if (entry.is_directory) {
                ++dir_count;
            } else if (entry.is_symlink) {
                ++symlink_count;
            } else {
                ++file_count;
                total_size += entry.size;
            }
        }

        *int cm = tar.getCompressionMethod();
        *int fmt = tar.getFormat();
        *string path = tar.getPath();
        tar.close();

        printf("%s %s\n", tc.key("Archive:"), tc.bold(path ?? archive_path));
        printf("%s %s\n", tc.key("Format:"), get_format_name(fmt ?? 0));
        printf("%s %s\n", tc.key("Compression:"), get_compression_name(cm ?? 0));
        printf("%s %s\n", tc.key("Entries:"), tc.number(string(entries.size())));
        printf("%s %s\n", tc.key("Files:"), tc.number(string(file_count)));
        printf("%s %s\n", tc.key("Directories:"), tc.number(string(dir_count)));
        if (symlink_count > 0) {
            printf("%s %s\n", tc.key("Symlinks:"), tc.number(string(symlink_count)));
        }
        printf("%s %s\n", tc.key("Total size:"), tc.number(formatSize(total_size)));
    }

    # --- Encrypt command ---
    private cmdEncrypt() {
        hash<auto> opts = (new GetOpt(EncryptOpts)).parse3(\ARGV);
        if (opts.help) {
            usageEncrypt();
            return;
        }

        if (ARGV.size() < 2) {
            stderr.printf("%s encrypt requires <archive> <output>\n", tc.error("error:"));
            exit(1);
        }

        string input_path = shift ARGV;
        string output_path = shift ARGV;

        binary archive_data = ReadOnlyFile::readBinaryFile(input_path);

        binary encrypted;
        if (opts.password) {
            # Password mode with PBKDF2
            binary salt = get_random_bytes(SaltSize);
            binary key = hmac("sha256", salt, opts.password);
            binary iv = get_random_bytes(IVSize);
            binary ciphertext = encrypt(Cipher, archive_data, key, iv);
            encrypted = PasswordMagic + salt + iv + ciphertext;
        } else {
            binary key = getKey(opts);
            binary iv = get_random_bytes(IVSize);
            binary ciphertext = encrypt(Cipher, archive_data, key, iv);
            encrypted = iv + ciphertext;
        }

        File f();
        f.open(output_path, O_CREAT | O_WRONLY | O_TRUNC, 0600);
        f.write(encrypted);

        stderr.printf("%s encrypted %s -> %s (%s -> %s)\n",
            tc.success("ok:"),
            tc.bold(input_path),
            tc.bold(output_path),
            tc.dim(formatSize(archive_data.size())),
            tc.dim(formatSize(encrypted.size())),
        );
    }

    # --- Decrypt command ---
    private cmdDecrypt() {
        hash<auto> opts = (new GetOpt(DecryptOpts)).parse3(\ARGV);
        if (opts.help) {
            usageDecrypt();
            return;
        }

        if (ARGV.size() < 2) {
            stderr.printf("%s decrypt requires <encrypted-file> <output>\n", tc.error("error:"));
            exit(1);
        }

        string input_path = shift ARGV;
        string output_path = shift ARGV;

        binary encrypted = ReadOnlyFile::readBinaryFile(input_path);

        binary archive_data;
        if (opts.password || (encrypted.size() >= 4 && encrypted.substr(0, 4) == PasswordMagic)) {
            # Password mode (auto-detected or explicit)
            if (!opts.password) {
                throw "TAR-ERROR", "encrypted file uses password-based encryption; use -p <password>";
            }
            int min_pw_size = 4 + SaltSize + IVSize + 16;
            if (encrypted.size() < min_pw_size) {
                throw "TAR-ERROR", sprintf("encrypted file too small for password mode (%d bytes)",
                    encrypted.size());
            }
            binary salt = encrypted.substr(4, SaltSize);
            binary iv = encrypted.substr(4 + SaltSize, IVSize);
            binary ciphertext = encrypted.substr(4 + SaltSize + IVSize);
            binary key = hmac("sha256", salt, opts.password);
            archive_data = decrypt_to_binary(Cipher, ciphertext, key, iv);
        } else {
            binary key = getKey(opts);
            int min_size = IVSize + 16;
            if (encrypted.size() < min_size) {
                throw "TAR-ERROR", sprintf("encrypted file too small (%d bytes); minimum is %d bytes",
                    encrypted.size(), min_size);
            }
            binary iv = encrypted.substr(0, IVSize);
            binary ciphertext = encrypted.substr(IVSize);
            archive_data = decrypt_to_binary(Cipher, ciphertext, key, iv);
        }

        File f();
        f.open(output_path, O_CREAT | O_WRONLY | O_TRUNC);
        f.write(archive_data);

        stderr.printf("%s decrypted %s -> %s (%s)\n",
            tc.success("ok:"),
            tc.bold(input_path),
            tc.bold(output_path),
            tc.dim(formatSize(archive_data.size())),
        );
    }

    # --- Cat command ---
    private cmdCat() {
        if (!ARGV || ARGV[0] == "-h" || ARGV[0] == "--help") {
            usageCat();
            return;
        }

        if (ARGV.size() < 2) {
            stderr.printf("%s cat requires <archive> <entry-name>\n", tc.error("error:"));
            exit(1);
        }

        string archive_path = shift ARGV;
        string entry_name = shift ARGV;

        TarFile tar(archive_path, "r");
        if (!tar.hasEntry(entry_name)) {
            tar.close();
            throw "TAR-ERROR", sprintf("entry %y not found in archive", entry_name);
        }

        binary data = tar.read(entry_name);
        tar.close();
        stdout.write(data);
    }

    # --- Verify command ---
    private cmdVerify() {
        if (!ARGV || ARGV[0] == "-h" || ARGV[0] == "--help") {
            usageVerify();
            return;
        }

        string archive_path = shift ARGV;
        TarFile tar(archive_path, "r");
        list<hash<TarEntryInfo>> entries = tar.entries();

        *int cm = tar.getCompressionMethod();
        *int fmt = tar.getFormat();

        int total_size = 0;
        int file_count = 0;
        int error_count = 0;

        foreach hash<TarEntryInfo> entry in (entries) {
            if (!entry.is_directory && !entry.is_symlink && !entry.is_hardlink) {
                try {
                    binary content = tar.read(entry.name);
                    total_size += content.size();
                    ++file_count;
                    if (content.size() != entry.size) {
                        stderr.printf("  %s %s: size mismatch (expected %d, got %d)\n",
                            tc.error("FAIL"), entry.name, entry.size, content.size());
                        ++error_count;
                    }
                } catch (hash<ExceptionInfo> ex) {
                    stderr.printf("  %s %s: %s: %s\n",
                        tc.error("FAIL"), entry.name, ex.err, ex.desc);
                    ++error_count;
                }
            }
        }

        tar.close();

        printf("%s %s\n", tc.key("Archive:"), tc.bold(archive_path));
        printf("%s %s\n", tc.key("Entries:"), tc.number(string(entries.size())));
        printf("%s %s\n", tc.key("Files verified:"), tc.number(string(file_count)));
        printf("%s %s\n", tc.key("Total data:"), tc.number(formatSize(total_size)));
        printf("%s %s\n", tc.key("Compression:"), get_compression_name(cm ?? 0));
        printf("%s %s\n", tc.key("Format:"), get_format_name(fmt ?? 0));

        if (error_count) {
            printf("%s %s\n", tc.key("Result:"),
                tc.error(sprintf("FAILED (%d error%s)", error_count,
                    error_count == 1 ? "" : "s")));
            exit(1);
        } else {
            printf("%s %s\n", tc.key("Result:"), tc.success("OK"));
        }
    }

    #! Check if a path looks like a tar archive (by extension)
    private bool isArchivePath(string path) {
        string lower = path.lwr();
        return lower.endsWith(".tar") || lower.endsWith(".tar.gz") || lower.endsWith(".tgz")
            || lower.endsWith(".tar.bz2") || lower.endsWith(".tbz2") || lower.endsWith(".tar.xz")
            || lower.endsWith(".txz") || lower.endsWith(".tar.zst") || lower.endsWith(".tar.lz4");
    }

    # --- Diff command ---
    private cmdDiff() {
        if (!ARGV || ARGV[0] == "-h" || ARGV[0] == "--help") {
            usageDiff();
            return;
        }

        if (ARGV.size() < 1) {
            stderr.printf("%s diff requires <archive> <directory|archive>\n", tc.error("error:"));
            exit(1);
        }

        string archive_path = shift ARGV;
        string second_arg = ARGV ? shift ARGV : ".";

        # Detect archive-to-archive diff vs archive-to-filesystem diff
        if (is_file(second_arg) && isArchivePath(second_arg)) {
            cmdDiffArchives(archive_path, second_arg);
            return;
        }
        string directory = second_arg;

        TarFile tar(archive_path, "r");
        list<hash<TarEntryInfo>> entries = tar.entries();

        int matched = 0;
        int modified = 0;
        int archive_only = 0;

        # Track archive entry names for detecting disk-only files
        hash<string, bool> archive_names;

        foreach hash<TarEntryInfo> entry in (entries) {
            archive_names{entry.name} = True;
            string fs_path = directory + "/" + entry.name;

            if (entry.is_directory) {
                if (is_dir(fs_path)) {
                    ++matched;
                } else {
                    printf("  %s %s %s\n", tc.yellow("A"), tc.dim("dir "), entry.name);
                    ++archive_only;
                }
            } else if (entry.is_symlink) {
                if (is_link(fs_path)) {
                    string target = readlink(fs_path);
                    if (target == entry.link_target) {
                        ++matched;
                    } else {
                        printf("  %s %s %s (link target: %s vs %s)\n",
                            tc.red("M"), tc.dim("link"), entry.name,
                            entry.link_target, target);
                        ++modified;
                    }
                } else {
                    printf("  %s %s %s\n", tc.yellow("A"), tc.dim("link"), entry.name);
                    ++archive_only;
                }
            } else {
                # Regular file
                if (is_file(fs_path)) {
                    hash<StatInfo> st = hstat(fs_path);
                    if (st.size != entry.size) {
                        printf("  %s %s %s (size: %d vs %d)\n",
                            tc.red("M"), tc.dim("file"), entry.name,
                            entry.size, st.size);
                        ++modified;
                    } else {
                        # Same size — compare content
                        binary archive_content = tar.read(entry.name);
                        binary disk_content = ReadOnlyFile::readBinaryFile(fs_path);
                        if (archive_content == disk_content) {
                            ++matched;
                        } else {
                            printf("  %s %s %s (content differs)\n",
                                tc.red("M"), tc.dim("file"), entry.name);
                            ++modified;
                        }
                    }
                } else {
                    printf("  %s %s %s\n", tc.yellow("A"), tc.dim("file"), entry.name);
                    ++archive_only;
                }
            }
        }

        tar.close();

        # Scan filesystem for files not in archive
        int disk_only = 0;
        scanDiskOnly(directory, "", archive_names, \disk_only);

        # Summary
        printf("\n");
        if (matched > 0) {
            printf("  %s matched\n", tc.success(string(matched)));
        }
        if (modified > 0) {
            printf("  %s modified\n", tc.error(string(modified)));
        }
        if (archive_only > 0) {
            printf("  %s archive only\n", tc.warning(string(archive_only)));
        }
        if (disk_only > 0) {
            printf("  %s disk only\n", tc.warning(string(disk_only)));
        }

        if (modified > 0 || archive_only > 0 || disk_only > 0) {
            exit(1);
        }
    }

    #! Recursively scan for files on disk not in the archive
    private scanDiskOnly(string fs_path, string prefix, hash<string, bool> archive_names,
            reference<int> count) {
        Dir d();
        try {
            d.chdir(fs_path);
        } catch (hash<ExceptionInfo> ex) {
            stderr.printf("  %s cannot read directory %s: %s\n",
                tc.error("error:"), fs_path, ex.desc);
            return;
        }

        foreach string name in (d.listFiles()) {
            string rel = prefix ? prefix + "/" + name : name;
            if (!archive_names{rel}) {
                printf("  %s %s %s\n", tc.cyan("D"), tc.dim("file"), rel);
                ++count;
            }
        }

        foreach string name in (d.listDirs()) {
            string rel = prefix ? prefix + "/" + name : name;
            string dir_rel = rel + "/";
            if (!archive_names{dir_rel} && !archive_names{rel}) {
                printf("  %s %s %s\n", tc.cyan("D"), tc.dim("dir "), rel + "/");
                ++count;
            }
            scanDiskOnly(fs_path + "/" + name, rel, archive_names, \count);
        }
    }

    # --- Archive-to-archive diff ---
    private cmdDiffArchives(string path1, string path2) {
        TarFile tar1(path1, "r");
        TarFile tar2(path2, "r");

        list<hash<TarEntryInfo>> entries1 = tar1.entries();
        list<hash<TarEntryInfo>> entries2 = tar2.entries();

        # Build lookup hashes
        hash<string, hash<TarEntryInfo>> map1 = map {$1.name: $1}, entries1;
        hash<string, hash<TarEntryInfo>> map2 = map {$1.name: $1}, entries2;

        # Merged key set
        hash<string, bool> all_names;
        foreach hash<TarEntryInfo> e in (entries1) { all_names{e.name} = True; }
        foreach hash<TarEntryInfo> e in (entries2) { all_names{e.name} = True; }

        int matched = 0;
        int modified = 0;
        int only1 = 0;
        int only2 = 0;

        foreach string name in (keys all_names) {
            *hash<TarEntryInfo> e1 = map1{name};
            *hash<TarEntryInfo> e2 = map2{name};

            if (!e1) {
                printf("  %s %s\n", tc.cyan("B"), name);
                ++only2;
            } else if (!e2) {
                printf("  %s %s\n", tc.yellow("A"), name);
                ++only1;
            } else if (e1.is_directory && e2.is_directory) {
                ++matched;
            } else if (e1.size != e2.size) {
                printf("  %s %s (size: %d vs %d)\n",
                    tc.red("M"), name, e1.size, e2.size);
                ++modified;
            } else if (!e1.is_directory && !e1.is_symlink) {
                # Same size — compare content
                binary c1 = tar1.read(name);
                binary c2 = tar2.read(name);
                if (c1 == c2) {
                    ++matched;
                } else {
                    printf("  %s %s (content differs)\n", tc.red("M"), name);
                    ++modified;
                }
            } else {
                ++matched;
            }
        }

        tar1.close();
        tar2.close();

        # Summary
        printf("\n");
        printf("  %s: %s\n", tc.dim("archive A"), tc.bold(path1));
        printf("  %s: %s\n", tc.dim("archive B"), tc.bold(path2));
        if (matched > 0) {
            printf("  %s matched\n", tc.success(string(matched)));
        }
        if (modified > 0) {
            printf("  %s modified\n", tc.error(string(modified)));
        }
        if (only1 > 0) {
            printf("  %s only in A\n", tc.warning(string(only1)));
        }
        if (only2 > 0) {
            printf("  %s only in B\n", tc.info(string(only2)));
        }

        if (modified > 0 || only1 > 0 || only2 > 0) {
            exit(1);
        }
    }

    # --- Helpers ---

    #! Count entries in a directory tree (for progress total)
    private int countEntries(string fs_path, *hash<string, bool> visited) {
        string canonical = realpath(fs_path);
        if (visited{canonical}) {
            return 0;
        }
        visited{canonical} = True;

        int count = 1;  # The directory itself
        Dir d();
        d.chdir(fs_path);
        count += d.listFiles().size();

        foreach string name in (d.listDirs()) {
            string full_path = fs_path + "/" + name;
            if (is_link(full_path)) {
                ++count;
            } else {
                count += countEntries(full_path, visited);
            }
        }

        return count;
    }

    #! Walk a directory recursively, adding entries to the tar archive
    private int walkDirectory(TarFile tar, string fs_path, string archive_prefix,
            bool dereference, bool verbose, *hash<string, bool> visited,
            *reference<int> progress_count, int total = -1) {
        # Symlink loop detection via canonical path tracking
        string canonical = realpath(fs_path);
        if (visited{canonical}) {
            return 0;
        }
        visited{canonical} = True;

        tar.addDirectory(archive_prefix.endsWith("/") ? archive_prefix : archive_prefix + "/");
        int local_count = 1;
        if (verbose) {
            if (total >= 0) {
                ++progress_count;
                stderr.printf("[%d/%d] %s\n", progress_count, total, archive_prefix + "/");
            } else {
                stderr.printf("%s\n", archive_prefix + "/");
            }
        }

        Dir d();
        d.chdir(fs_path);

        foreach string name in (d.listFiles()) {
            string full_path = fs_path + "/" + name;
            string archive_name = archive_prefix + "/" + name;

            if (is_link(full_path) && !dereference) {
                tar.addSymlink(archive_name, readlink(full_path));
            } else {
                tar.addFile(archive_name, full_path);
            }
            ++local_count;
            if (verbose) {
                if (total >= 0) {
                    ++progress_count;
                    stderr.printf("[%d/%d] %s\n", progress_count, total, archive_name);
                } else {
                    stderr.printf("%s\n", archive_name);
                }
            }
        }

        foreach string name in (d.listDirs()) {
            string full_path = fs_path + "/" + name;
            string archive_name = archive_prefix + "/" + name;

            if (is_link(full_path) && !dereference) {
                tar.addSymlink(archive_name, readlink(full_path));
                ++local_count;
                if (verbose) {
                    if (total >= 0) {
                        ++progress_count;
                        stderr.printf("[%d/%d] %s\n", progress_count, total, archive_name);
                    } else {
                        stderr.printf("%s\n", archive_name);
                    }
                }
            } else {
                local_count += walkDirectory(tar, full_path, archive_name, dereference,
                    verbose, visited, \progress_count, total);
            }
        }

        return local_count;
    }

    #! Get compression method from command-line flags or filename extension
    private int getCompressionFromOpts(hash<auto> opts, string filename) {
        if (opts.gzip) { return TAR_CM_GZIP; }
        if (opts.bzip2) { return TAR_CM_BZIP2; }
        if (opts.xz) { return TAR_CM_XZ; }
        if (opts.zstd) { return TAR_CM_ZSTD; }
        if (opts.lz4) { return TAR_CM_LZ4; }

        # Auto-detect from filename
        string lower = filename.lwr();
        HashIterator it(CompressionExtMap);
        while (it.next()) {
            if (lower.endsWith(it.getKey())) {
                return it.getValue();
            }
        }

        return TAR_CM_NONE;
    }

    #! Get encryption key from command-line opts
    private binary getKey(hash<auto> opts) {
        if (opts.gen_key) {
            binary key = get_random_bytes(KeySize);
            stderr.printf("%s %s\n", tc.key("Generated key:"), key.toHex());
            return key;
        }

        if (opts.key_file) {
            binary key = ReadOnlyFile::readBinaryFile(opts.key_file);
            if (key.size() != KeySize) {
                throw "TAR-ERROR", sprintf("key file must be exactly %d bytes; got %d bytes",
                    KeySize, key.size());
            }
            return key;
        }

        if (opts.key) {
            string hex = opts.key;
            if (hex.size() != KeySize * 2) {
                throw "TAR-ERROR", sprintf("hex key must be exactly %d hex characters (= %d bytes); "
                    "got %d characters", KeySize * 2, KeySize, hex.size());
            }
            return parse_hex_string(hex);
        }

        throw "TAR-ERROR", "encryption key required: use -k <hex>, -K <file>, -p <password>, "
            "or --gen-key";
    }

    #! Format file mode as rwx string
    private string formatMode(int mode) {
        string result = "";
        result += (mode & 0400) ? "r" : "-";
        result += (mode & 0200) ? "w" : "-";
        result += (mode & 0100) ? "x" : "-";
        result += (mode & 0040) ? "r" : "-";
        result += (mode & 0020) ? "w" : "-";
        result += (mode & 0010) ? "x" : "-";
        result += (mode & 0004) ? "r" : "-";
        result += (mode & 0002) ? "w" : "-";
        result += (mode & 0001) ? "x" : "-";
        return result;
    }

    #! Format byte size with human-readable units
    private string formatSize(int bytes) {
        if (bytes < 1024) {
            return sprintf("%d B", bytes);
        }
        if (bytes < 1024 * 1024) {
            return sprintf("%.1f KB", bytes / 1024.0);
        }
        if (bytes < 1024 * 1024 * 1024) {
            return sprintf("%.1f MB", bytes / (1024.0 * 1024.0));
        }
        return sprintf("%.1f GB", bytes / (1024.0 * 1024.0 * 1024.0));
    }

    # --- Usage ---

    #! Format a command entry for the help text with aligned columns
    private string fmtCmd(string name, *string alias, string desc) {
        # Pad command name to 7 chars (length of "extract"/"encrypt"/"decrypt")
        string padded = name + strmul(" ", 7 - name.length());
        if (alias) {
            return sprintf("  %s %s  %s", tc.yellow(alias), tc.bold(padded), desc);
        }
        return sprintf("    %s  %s", tc.bold(padded), desc);
    }

    private usage() {
        printf("%s - Qore TAR archive tool\n\n", tc.bold("qtar"));
        printf("%s qtar <command> [options] <archive> [files...]\n\n", tc.key("Usage:"));
        printf("%s\n", tc.key("Commands:"));
        printf("%s\n", fmtCmd("create",  "c", "Create a new archive"));
        printf("%s\n", fmtCmd("extract", "x", "Extract archive contents"));
        printf("%s\n", fmtCmd("list",    "t", "List archive contents"));
        printf("%s\n", fmtCmd("add",     "a", "Add files to an existing archive"));
        printf("%s\n", fmtCmd("info",    "i", "Show archive metadata"));
        printf("%s\n", fmtCmd("encrypt", "e", "Encrypt an archive (AES-256-CBC)"));
        printf("%s\n", fmtCmd("decrypt", "d", "Decrypt an encrypted archive"));
        printf("%s\n", fmtCmd("cat",     NOTHING, "Read a single entry to stdout"));
        printf("%s\n", fmtCmd("verify",  NOTHING, "Verify archive integrity"));
        printf("%s\n", fmtCmd("diff",    NOTHING, "Compare archive vs filesystem"));
        printf("\n%s\n", tc.key("Options:"));
        printf("  %s          Show help (or command-specific help)\n", tc.dim("-h, --help"));
        printf("  %s       Show version\n", tc.dim("-V, --version"));
        printf("\n%s\n", tc.key("Examples:"));
        printf("  qtar create backup.tar.gz /path/to/project\n");
        printf("  qtar extract backup.tar.gz -C /tmp/restore\n");
        printf("  qtar list -l archive.tar\n");
        printf("  qtar extract archive.tar --include='*.txt' --exclude='tmp/*'\n");
        printf("  qtar encrypt archive.tar archive.tar.enc --gen-key\n");
        printf("  qtar cat archive.tar.gz path/to/file.txt > output.txt\n");
    }

    private usageCreate() {
        printf("%s qtar create [options] <archive> <files/dirs...>\n\n", tc.key("Usage:"));
        printf("%s\n", tc.key("Compression (auto-detected from extension if not specified):"));
        printf("  %s           Gzip compression (.tar.gz, .tgz)\n", tc.dim("-z, --gzip"));
        printf("  %s          Bzip2 compression (.tar.bz2)\n", tc.dim("-j, --bzip2"));
        printf("  %s             XZ compression (.tar.xz)\n", tc.dim("-J, --xz"));
        printf("  %s             Zstandard compression (.tar.zst)\n", tc.dim("    --zstd"));
        printf("  %s              LZ4 compression (.tar.lz4)\n", tc.dim("    --lz4"));
        printf("  %s       Compression level (1-9)\n", tc.dim("-l, --level=N"));
        printf("\n%s\n", tc.key("Options:"));
        printf("  %s    Archive format: pax (default), ustar, gnu, v7\n", tc.dim("-f, --format=FMT"));
        printf("  %s   Follow symlinks\n", tc.dim("-L, --dereference"));
        printf("  %s  Change to DIR before adding files\n", tc.dim("-C, --directory=DIR"));
        printf("  %s       Verbose (list files as added)\n", tc.dim("-v, --verbose"));
    }

    private usageExtract() {
        printf("%s qtar extract [options] <archive>\n\n", tc.key("Usage:"));
        printf("%s\n", tc.key("Options:"));
        printf("  %s  Extract to DIR (default: .)\n", tc.dim("-C, --directory=DIR"));
        printf("  %s   Include only matching entries (repeatable)\n",
            tc.dim("    --include=GLOB"));
        printf("  %s   Exclude matching entries (repeatable)\n", tc.dim("    --exclude=GLOB"));
        printf("  %s      Strip N leading path components\n", tc.dim("    --strip=N"));
        printf("  %s    Do not preserve permissions\n", tc.dim("    --no-preserve"));
        printf("  %s  Do not overwrite existing files\n", tc.dim("    --no-overwrite"));
        printf("  %s       Verbose (list files as extracted)\n", tc.dim("-v, --verbose"));
    }

    private usageList() {
        printf("%s qtar list [options] <archive>\n\n", tc.key("Usage:"));
        printf("%s\n", tc.key("Options:"));
        printf("  %s      Long listing (permissions, size, date)\n", tc.dim("-l, --long"));
        printf("  %s   Same as --long\n", tc.dim("-v, --verbose"));
    }

    private usageAdd() {
        printf("%s qtar add [options] <archive> <files/dirs...>\n\n", tc.key("Usage:"));
        printf("%s\n", tc.key("Options:"));
        printf("  %s   Follow symlinks\n", tc.dim("-L, --dereference"));
        printf("  %s  Change to DIR before adding files\n", tc.dim("-C, --directory=DIR"));
        printf("  %s       Verbose (list files as added)\n", tc.dim("-v, --verbose"));
    }

    private usageInfo() {
        printf("%s qtar info <archive>\n", tc.key("Usage:"));
    }

    private usageEncrypt() {
        printf("%s qtar encrypt [options] <archive> <output>\n\n", tc.key("Usage:"));
        printf("%s\n", tc.key("Options:"));
        printf("  %s  Encryption password (PBKDF2 key derivation)\n", tc.dim("-p, --password=PASS"));
        printf("  %s     Hex-encoded 32-byte key (64 hex chars)\n", tc.dim("-k, --key=KEY"));
        printf("  %s  Read raw 32-byte key from file\n", tc.dim("-K, --key-file=FILE"));
        printf("  %s       Generate random key (printed to stderr)\n", tc.dim("    --gen-key"));
    }

    private usageDecrypt() {
        printf("%s qtar decrypt [options] <encrypted-file> <output>\n\n", tc.key("Usage:"));
        printf("%s\n", tc.key("Options:"));
        printf("  %s  Decryption password (mode auto-detected)\n", tc.dim("-p, --password=PASS"));
        printf("  %s     Hex-encoded 32-byte key (64 hex chars)\n", tc.dim("-k, --key=KEY"));
        printf("  %s  Read raw 32-byte key from file\n", tc.dim("-K, --key-file=FILE"));
    }

    private usageCat() {
        printf("%s qtar cat <archive> <entry-name>\n", tc.key("Usage:"));
    }

    private usageVerify() {
        printf("%s qtar verify <archive>\n\n", tc.key("Usage:"));
        printf("Reads all entries and data blocks to verify archive integrity.\n");
        printf("Exits with code 0 if valid, 1 if errors found.\n");
    }

    private usageDiff() {
        printf("%s qtar diff <archive> <directory|archive>\n\n", tc.key("Usage:"));
        printf("Compares archive contents against a filesystem directory or another archive.\n");
        printf("Archive-to-archive mode is auto-detected when the second argument has a\n");
        printf("tar extension (.tar, .tar.gz, .tgz, etc.).\n\n");
        printf("%s\n", tc.key("Legend (archive vs directory):"));
        printf("  %s  Modified (content or metadata differs)\n", tc.red("M"));
        printf("  %s  Archive only (not on disk)\n", tc.yellow("A"));
        printf("  %s  Disk only (not in archive)\n", tc.cyan("D"));
        printf("\n%s\n", tc.key("Legend (archive vs archive):"));
        printf("  %s  Modified (size or content differs)\n", tc.red("M"));
        printf("  %s  Only in first archive\n", tc.yellow("A"));
        printf("  %s  Only in second archive\n", tc.cyan("B"));
    }
}
