#!/usr/bin/env qore
# -*- mode: qore; indent-tabs-mode: nil -*-
# @file qget downloads files from http, https, ftp, ftps, and other URLs

/*  qget Copyright 2011 - 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.
*/

%requires qore >= 3.0

%modern

%requires Util
%requires TerminalFormat
%requires UrlDownloader

%exec-class QgetApp

#! Shows the events of a download in the progress display
class QgetListener inherits UrlDownloadListener {
    private {
        QgetApp app;
        #! the URL downloaded
        string url;
        #! the ID of the transfer in the progress display, once the download has started
        *int id;
    }

    constructor(QgetApp app, string url) {
        self.app = app;
        self.url = url;
    }

    redirected(hash<HttpRedirectInfo> info) {
        app.info(sprintf("%s %s %s", QgetApp::color.dim(sprintf("↪ %d", info.status_code)),
            QgetApp::color.dim("→"), QgetApp::color.dim(info.target_url)));
    }

    started(hash<UrlDownloadStartInfo> info) {
        if (app.verbose) {
            app.info(sprintf("%s %s%s%s", QgetApp::color.dim(info.protocol),
                QgetApp::color.number(string(info.status_code)),
                info.content_type ? " " + QgetApp::color.dim(info.content_type) : "",
                exists info.total ? " " + QgetApp::color.dim(TerminalProgress::formatBytes(info.total)) : ""));
        }
        if (*TerminalProgress progress = app.progress) {
            string label = info.file ? basename(info.file) : (UrlDownloader::getFileNameFromUrl(url) ?? url);
            id = progress.add(label, info.total);
            progress.setInfo(id, info.protocol);
        }
    }

    progress(int done, *int total) {
        if (exists id) {
            app.progress.update(id, done);
        }
    }

    #! Removes the transfer from the progress display and writes the given message, if any
    finish(*string message) {
        if (exists id) {
            app.progress.finish(id, message);
            remove id;
        } else if (!message) {
            return;
        } else if (app.progress) {
            app.progress.log(message);
        } else {
            stderr.print(message + "\n");
        }
    }

    #! Returns a summary of the transfer, if it started
    *string getSummary() {
        if (exists id) {
            return app.progress.getSummary(id);
        }
    }
}

public class QgetApp {
    public {
        #! the colors of the output on stderr
        static TerminalColor color;

        #! the progress display, if progress is shown
        *TerminalProgress progress;

        #! the level of verbosity
        int verbose = 0;

        #! the level of quiet: 1 shows no progress or information, 2 shows no errors either
        int quiet = 0;
    }

    private {
        const Version = "2.0.0";

        const Opts = {
            "output": "o,output=s",
            "output_document": "O,output-document=s",
            "dir": "directory-prefix=s",
            "no_clobber": "no-clobber",
            "no_part": "no-part",
            "content_disposition": "content-disposition",
            "headers": "H,header=s@",
            "user_agent": "A,user-agent=s",
            "user": "u,user=s",
            "proxy": "x,proxy=s",
            "old_proxy": "P=s",
            "no_proxy": "no-proxy",
            "http11": "http1.1",
            "http2": "http2",
            "http3": "http3",
            "insecure": "k,insecure",
            "cacert": "cacert=s",
            "capath": "capath=s",
            "cert": "E,cert=s",
            "key": "key=s",
            "max_redirs": "max-redirs=i",
            "max_redirect": "max-redirect=i",
            "compressed": "compressed",
            "connect_timeout": "connect-timeout=s",
            "read_timeout": "read-timeout=s",
            "max_time": "m,max-time=s",
            "timeout": "T,timeout=s",
            "fail_with_body": "fail-with-body",
            "quiet": "q,quiet:i+",
            "silent": "s,silent",
            "verbose": "v,verbose:i+",
            "full_exceptions": "full-exceptions",
            "old_full_exceptions": "e",
            "nocolor": "no-color",
            "help": "h,help",
            "version": "V,version",
        };

        #! the exit code for each download error
        const ExitCodes = {
            "DOWNLOAD-ERROR": 1,
            "DOWNLOAD-URL-ERROR": 2,
            "DOWNLOAD-IO-ERROR": 3,
            "DOWNLOAD-NETWORK-ERROR": 4,
            "DOWNLOAD-TLS-ERROR": 5,
            "DOWNLOAD-AUTH-ERROR": 6,
            "DOWNLOAD-PROTOCOL-ERROR": 7,
            "DOWNLOAD-SERVER-ERROR": 8,
            "DOWNLOAD-FILE-EXISTS": 10,
            "DOWNLOAD-TIMEOUT": 11,
            "DOWNLOAD-CANCELLED": 130,
        };

        #! the exit code for invalid arguments
        const UsageError = 2;

        #! the interval at which the progress display is refreshed, so a download without progress is shown as
        #! stalled
        const RefreshInterval = 250ms;

        hash<auto> opts;

        #! the downloader
        UrlDownloader dl;

        #! set when the downloads are done, to stop refreshing the progress display
        Mutex refresh_lock();
        Condition refresh_cond();
        bool refresh_done = False;
        Counter refresh_counter();
    }

    constructor() {
        GetOpt getopt(Opts);
        try {
            opts = getopt.parse2(\ARGV);
        } catch (hash<ExceptionInfo> ex) {
            color = new TerminalColor(True, stderr);
            error(ex.desc);
            exit(UsageError);
        }

        color = new TerminalColor(!opts.nocolor, stderr);
        quiet = opts.silent ? 2 : (opts.quiet ?? 0);
        verbose = opts.verbose ?? 0;

        if (opts.version) {
            printf("qget %s\n", Version);
            exit(0);
        }
        if (opts.help) {
            QgetApp::usage(new TerminalColor(!opts.nocolor));
            exit(0);
        }

        # deprecated options
        if (exists opts.old_proxy) {
            warning("-P is deprecated for --proxy and will be removed; use -x or --proxy");
            if (!exists opts.proxy) {
                opts.proxy = opts.old_proxy;
            }
        }
        if (opts.old_full_exceptions) {
            warning("-e is deprecated for --full-exceptions and will be removed; use --full-exceptions");
            opts.full_exceptions = True;
        }

        list<string> urls = ARGV;
        # the former syntax for a connection name with a separate path: "qget name /path"
        if (urls.size() == 2 && urls[0] !~ /:\/\// && urls[0] !~ /\// && urls[1] =~ /^\//) {
            urls = (urls[0] + urls[1],);
        }
        if (!urls) {
            error("no URL given; try 'qget --help'");
            exit(UsageError);
        }

        hash<UrlDownloadOptions> dopts;
        try {
            dopts = getDownloadOptions(urls.size());
        } catch (hash<ExceptionInfo> ex) {
            error(ex.desc);
            exit(UsageError);
        }
        try {
            dl = new UrlDownloader(dopts);
        } catch (hash<ExceptionInfo> ex) {
            error(ex.desc);
            exit(ExitCodes{ex.err} ?? UsageError);
        }

        if (!quiet) {
            progress = new TerminalProgress(<TerminalProgressOptions>{
                "color": color.enabled,
                "total_line": urls.size() > 1,
            });
        }

        # Ctrl-C cancels the download in progress and keeps the data received; a second one exits immediately
        set_signal_handler(SIGINT, sub (softint sig) {
            if (dl.isCancelled()) {
                exit(ExitCodes."DOWNLOAD-CANCELLED");
            }
            dl.cancel();
        });

        startRefresh();
        int rc = 0;
        try {
            rc = run(urls);
        } catch (hash<ExceptionInfo> ex) {
            error(opts.full_exceptions ? get_exception_string(ex) : sprintf("%s: %s", ex.err, ex.desc));
            rc = 1;
        }
        stopRefresh();
        if (progress) {
            progress.close();
        }
        remove_signal_handler(SIGINT);
        exit(rc);
    }

    #! Writes an informational message unless quiet
    info(string msg) {
        if (quiet) {
            return;
        }
        if (progress) {
            progress.log(msg);
        } else {
            stderr.print(msg + "\n");
        }
    }

    #! Writes a warning unless quiet
    warning(string msg) {
        if (quiet) {
            return;
        }
        stderr.print(sprintf("%s %s\n", color.yellow("qget:"), color.yellow(msg)));
    }

    #! Writes an error unless silent
    error(string msg) {
        if (quiet > 1) {
            return;
        }
        string str = sprintf("%s %s", color.red("qget:"), msg);
        if (progress) {
            progress.log(str);
        } else {
            stderr.print(str + "\n");
        }
    }

    #! Downloads the URLs and returns the exit code
    /** the exit code of the first error with the lowest exit code, as with wget; a cancellation stops the
        downloads
    */
    private int run(list<string> urls) {
        int rc = 0;
        int start = clock_getmicros();
        int ok = 0;
        int failed = 0;
        int bytes = 0;
        on_exit if (urls.size() > 1 && !quiet) {
            string time = TerminalProgress::formatElapsed(clock_getmicros() - start);
            if (failed) {
                info(sprintf("%s %s", color.red("✘"), color.bold(sprintf("%d of %d downloads failed", failed,
                    ok + failed))));
            } else {
                info(sprintf("%s %s %s", color.green("✔"), color.bold(sprintf("%d downloads", ok)),
                    color.dim(sprintf("%s in %s", TerminalProgress::formatBytes(bytes), time))));
            }
        }
        *StdoutOutputStream out = (opts.output == "-" || opts.output_document == "-")
            ? new StdoutOutputStream()
            : NOTHING;
        foreach string url in (urls) {
            QgetListener listener(self, url);
            try {
                hash<UrlDownloadResult> res = dl.download(url, listener, out);
                ++ok;
                bytes += res.size;
                string summary = listener.getSummary() ?? sprintf("%s", TerminalProgress::formatBytes(res.size));
                listener.finish(quiet
                    ? NOTHING
                    : sprintf("%s %s %s", color.green("✔"), res.file ? color.bold(res.file) : color.bold(url),
                        color.dim(summary)));
            } catch (hash<ExceptionInfo> ex) {
                ++failed;
                int code = ExitCodes{ex.err} ?? 1;
                string msg = sprintf("%s %s", color.red("✘"), ex.desc);
                if (ex.arg.part_file) {
                    msg += color.dim(sprintf("; the data received is kept in %s", ex.arg.part_file));
                }
                if (opts.full_exceptions && ex.arg.cause) {
                    msg += "\n" + get_exception_string(ex.arg.cause);
                }
                listener.finish(quiet > 1 ? NOTHING : msg);
                if (!rc || code < rc) {
                    rc = code;
                }
                if (ex.err == "DOWNLOAD-CANCELLED") {
                    return code;
                }
            }
        }
        return rc;
    }

    #! Returns the download options for the command-line options
    private hash<UrlDownloadOptions> getDownloadOptions(int url_count) {
        hash<UrlDownloadOptions> rv();
        *string output = opts.output ?? opts.output_document;
        if (output) {
            if (output != "-" && url_count > 1) {
                throw "QGET-ERROR", "an output file can only be given for a single URL";
            }
            rv.output = output;
        }
        if (opts.dir) {
            rv.output_dir = opts.dir;
        }
        if (opts.no_clobber) {
            rv.clobber = False;
        }
        if (opts.no_part) {
            rv.part_file = False;
        }
        if (opts.content_disposition) {
            rv.content_disposition = True;
        }
        foreach string h in (opts.headers) {
            *list<*string> m = (h =~ x/^([^:]+):\s*(.*)$/s);
            if (!m || !m[0].val()) {
                throw "QGET-ERROR", sprintf("invalid header %y; expecting \"name: value\"", h);
            }
            string name = m[0];
            rv.headers{trim(name)} = m[1] ?? "";
        }
        if (opts.user_agent) {
            rv.user_agent = opts.user_agent;
        } else {
            rv.user_agent = "qget/" + Version;
        }
        if (opts.user) {
            rv.user = opts.user;
        }
        if (opts.proxy) {
            rv.proxy = opts.proxy;
        }
        if (opts.no_proxy) {
            rv.env_proxy = False;
        }
        int versions = (opts.http11 ? 1 : 0) + (opts.http2 ? 1 : 0) + (opts.http3 ? 1 : 0);
        if (versions > 1) {
            throw "QGET-ERROR", "only one of --http1.1, --http2, and --http3 can be given";
        }
        if (opts.http11) {
            rv.http_version = "1.1";
        } else if (opts.http2) {
            rv.http_version = "2";
        } else if (opts.http3) {
            rv.http_version = "3";
        }
        if (opts.insecure) {
            rv.verify = False;
        }
        if (opts.cacert) {
            rv.ca_file = opts.cacert;
        }
        if (opts.capath) {
            rv.ca_path = opts.capath;
        }
        if (opts.cert) {
            rv.client_cert = opts.cert;
        }
        if (opts.key) {
            rv.client_key = opts.key;
        }
        if (exists opts.max_redirs || exists opts.max_redirect) {
            rv.max_redirects = opts.max_redirs ?? opts.max_redirect;
        }
        if (opts.compressed) {
            rv.compressed = True;
        }
        if (exists opts.timeout) {
            timeout t = QgetApp::getSeconds("--timeout", opts.timeout);
            rv.connect_timeout = t;
            rv.read_timeout = t;
        }
        if (exists opts.connect_timeout) {
            rv.connect_timeout = QgetApp::getSeconds("--connect-timeout", opts.connect_timeout);
        }
        if (exists opts.read_timeout) {
            rv.read_timeout = QgetApp::getSeconds("--read-timeout", opts.read_timeout);
        }
        if (exists opts.max_time) {
            rv.max_time = QgetApp::getSeconds("--max-time", opts.max_time);
        }
        if (opts.fail_with_body) {
            rv.keep_error_body = True;
        }
        return rv;
    }

    #! Returns a time in seconds given on the command line as a timeout
    private static timeout getSeconds(string opt, string val) {
        if (val !~ /^[0-9]+(\.[0-9]*)?$/ || val.toFloat() <= 0) {
            throw "QGET-ERROR", sprintf("invalid value %y for %s; expecting a positive number of seconds", val, opt);
        }
        return (val.toFloat() * 1000).toInt();
    }

    #! Starts refreshing the progress display, so a download without progress is shown as stalled
    private startRefresh() {
        if (!progress || !progress.isInteractive()) {
            return;
        }
        refresh_counter.inc();
        background sub () {
            on_exit refresh_counter.dec();
            AutoLock al(refresh_lock);
            while (!refresh_done) {
                # a timed wait: the display shows how long a transfer has been without progress
                refresh_cond.wait(refresh_lock, RefreshInterval);
                if (!refresh_done) {
                    progress.refresh();
                }
            }
        }();
    }

    #! Stops refreshing the progress display
    private stopRefresh() {
        {
            AutoLock al(refresh_lock);
            refresh_done = True;
            refresh_cond.signal();
        }
        refresh_counter.waitForZero();
    }

    private static printHelpLine(TerminalColor c, string opt, string desc, int width = 32) {
        # indent options without a short form by the width of a short option prefix ("-x, ") so that all long
        # options are aligned in the same column
        if (opt =~ /^--/) {
            opt = "    " + opt;
        }
        printf("  %s %s\n", TerminalColor::padRight(c.key(opt), width), desc);
    }

    static usage(TerminalColor c) {
        printf("%s - download files from URLs\n\n", c.bold("qget"));
        printf("%s\n", c.bold("USAGE"));
        printf("  qget [options] URL...\n");
        printf("  qget [options] connection[/path]\n\n");
        printf("%s\n", c.bold("URL SCHEMES"));
        printf("  %s\n\n", (sort(UrlDownloader::getSupportedSchemes())).join(", "));

        printf("%s\n", c.bold("OUTPUT"));
        printHelpLine(c, "-o, --output=FILE", "write to FILE; \"-\" writes to stdout");
        printHelpLine(c, "-O, --output-document=FILE", "same as --output");
        printHelpLine(c, "--directory-prefix=DIR", "save files in DIR");
        printHelpLine(c, "--no-clobber", "fail if a file exists instead of overwriting it");
        printHelpLine(c, "--no-part", "write directly to the file instead of a .part file");
        printHelpLine(c, "--content-disposition", "use the file name given by the server");
        printf("\n");

        printf("%s\n", c.bold("REQUEST"));
        printHelpLine(c, "-H, --header=\"NAME: VALUE\"", "add a request header (repeatable)");
        printHelpLine(c, "-A, --user-agent=AGENT", "set the User-Agent header");
        printHelpLine(c, "-u, --user=USER:PASSWORD", "credentials for Basic authentication or FTP");
        printHelpLine(c, "--compressed", "request a compressed response and decompress it");
        printHelpLine(c, "--max-redirs=N", "follow at most N redirects (default 20; 0: none)");
        printHelpLine(c, "--fail-with-body", "save the body of an HTTP error response");
        printHelpLine(c, "--http1.1, --http2, --http3", "use the given HTTP version");
        printf("\n");

        printf("%s\n", c.bold("CONNECTION"));
        printHelpLine(c, "-x, --proxy=URL", "use the given HTTP proxy");
        printHelpLine(c, "--no-proxy", "ignore the proxy environment variables");
        printHelpLine(c, "-k, --insecure", "do not verify server certificates");
        printHelpLine(c, "--cacert=FILE", "verify server certificates with the CAs in FILE");
        printHelpLine(c, "--capath=DIR", "verify server certificates with the CAs in DIR");
        printHelpLine(c, "-E, --cert=FILE", "client certificate (PEM)");
        printHelpLine(c, "--key=FILE", "private key of the client certificate (PEM)");
        printHelpLine(c, "--connect-timeout=SECS", "maximum time to connect (default 30)");
        printHelpLine(c, "--read-timeout=SECS", "maximum time to wait for data (default 120)");
        printHelpLine(c, "-m, --max-time=SECS", "maximum time for each download");
        printHelpLine(c, "-T, --timeout=SECS", "set the connect and read timeouts");
        printf("\n");

        printf("%s\n", c.bold("DISPLAY"));
        printHelpLine(c, "-q, --quiet", "no progress; -qq: no errors either");
        printHelpLine(c, "-s, --silent", "same as -qq");
        printHelpLine(c, "-v, --verbose", "show the protocol, status, and content type");
        printHelpLine(c, "--no-color", "do not use colors (also with NO_COLOR set)");
        printHelpLine(c, "--full-exceptions", "show full exception information");
        printHelpLine(c, "-V, --version", "show the version");
        printHelpLine(c, "-h, --help", "show this help");
        printf("\n");

        printf("%s\n", c.bold("EXIT CODES"));
        printf("  0 success, 1 other error, 2 invalid arguments, 3 file error, 4 network error, 5 TLS error,\n"
            "  6 authentication error, 7 protocol error, 8 server error, 10 file exists, 11 timeout,\n"
            "  130 interrupted\n");
    }
}
