#!/usr/bin/env qore
# -*- mode: qore; indent-tabs-mode: nil -*-

/*  Copyright 2013 - 2023 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 at least this qore version to run
%requires qore >= 0.8.12

%new-style
%strict-args
%require-types
%enable-all-warnings

%requires Sap4HanaRestClient
%requires Util
%requires ConnectionProvider

%try-module yaml >= 0.5
%define NoYaml
%endtry

%try-module xml >= 1.3
%define NoXml
%endtry

%try-module json >= 1.5
%define NoJson
%endtry

%exec-class SapRestClient

class SapRestClient {
    public {
        #! program options
        const Opts = {
            "sendenc":        "e,send-encoding:s",
            "data":           "S,serialization=s",
            "proxy":          "P,proxy-url=s",
            "show":           "W,show-url",
            "timeout":        "t,timeout=i",
            "lit":            "l,literal:i+",
            "reformat":       "R,reformat",
            "fullex":         "E,full-exception",
            "header":         "H,header=s@",
            "verbose":        "v,verbose:i+",

            "conn":           "c,connection=s",
            "apikey":         "k,apikey=s",
            "client_id":      "i,client-id=s",
            "client_secret":  "s,client_secret=s",

            "help":           "h,help",
        };

        #! recognized HTTP methods
        const Methods = {
            "GET": True,
            "PATCH": True,
            "PUT": True,
            "POST": True,
            "DELETE": True,
            "OPTIONS": True,
        };
    }

    constructor() {
        GetOpt g(Opts);
        hash<auto> opt = g.parse3(\ARGV);
        if (opt.help)
            usage();

        Sap4HanaRestClient rc;

        *string meth = shift ARGV;
        if (!exists meth)
            usage();

        *string url = shift ARGV;
        auto body;
        if (!Methods{meth.upr()}) {
            body = url;
            url = meth;
            meth = "GET";
        } else {
            meth = meth.upr();
            body = shift ARGV;
        }

        *string path;

        if (opt.conn) {
            try {
                AbstractConnection conn = get_connection(opt.conn);
                if (!(conn instanceof Sap4HanaRestConnection)) {
                    stderr.printf("connection %y is a %y object; expecting \"Sap4HanaRestClient; exiting\"\n", opt.conn, conn.className());
                    exit(1);
                }
                rc = conn.get();
                path = url;
                body = shift ARGV;
            } catch (hash<ExceptionInfo> ex) {
                stderr.printf("connection %y: %s: %s: %s\n", opt.conn, get_ex_pos(ex), ex.err, ex.desc);
                exit(1);
            }
        } else {
            if (!url) {
                printf("ERROR: missing URL for SAP server\n");
                usage();
            }
            opt.url = url;

            if ((opt.client_id || ENV.SAP_CLIENT_ID) && (opt.client_secret || ENV.SAP_CLIENT_SECRET)) {
                if (!opt.client_id) {
                    opt.client_id = ENV.SAP_CLIENT_ID;
                }
                if (!opt.client_secret) {
                    opt.client_secret = ENV.SAP_CLIENT_SECRET;
                }
            } else {
                opt.apikey = opt.apikey ?? ENV.SAP_APIKEY;
                if (!opt.apikey) {
                    error("missing --apikey / SAP_APIKEY env var or --client-id and --client-secret / SAP_CLIENT_ID "
                        "and SAP_CLIENT_SECRET env vars; cannot connect to SAP without authentication");
                }
            }
            hash<auto> sap_opts = opt - ("conn", "lit", "reformat", "fullex", "header", "show");
            rc = new Sap4HanaRestClient(sap_opts, True);
        }

        # set path
        if (path) {
            if (path =~ /^\//)
                path = path.substr(1);
            #printf("BASE URL: %y\n", rc.getURL());
            rc.setURL(rc.getURL() + "/" + path);
        }

        if (opt.show) {
            if (rc.getProxyURL())
                printf("%s (through HTTP proxy: %s)\n", rc.getURL(), rc.getProxyURL());
            else
                printf("%s\n", rc.getURL());
            thread_exit;
        }

        foreach string h in (opt.header) {
            (*string k, *string v) = (h =~ x/([^:]+):(.+)$/); #/);
            trim k;
            trim v;
            if (!k || !v) {
                stderr.printf("invalid header %y; expecting \"key: value\" format\n", h);
                exit(1);
            }
            rc.addDefaultHeaders((k: v));
        }

        if (exists body)
            body = parse_to_qore_value(body);

        if (opt.data) {
            if (!RestClient::DataSerializationOptions{opt.data})
                error("data serialization option %y is unknown; valid options: %y", opt.data, RestClient::DataSerializationOptions.keys());
            rc.setSerialization(opt.data);
        }

        if (opt.sendenc) {
            if (opt.sendenc === True)
                opt.sendenc = "deflate";
            else if (!RestClient::EncodingSupport{opt.sendenc})
                error("send encoding option %y is unknown; valid options: %y", opt.sendenc, RestClient::EncodingSupport.keys());
            rc.setSendEncoding(opt.sendenc);
        }

        if (opt.verbose)
            printf("SAP URL: %y\n", rc.getURL());

        hash<auto> hdr;
        hash<auto> info;

        try {
            hash<auto> h;
            on_exit if (opt.lit) {
                showRestRequest(info, body, opt);
                showRestResponse(info, h.body, opt);
            }

            h = rc.doRequest(meth, "", body, \info, NOTHING, hdr);
            if (!opt.lit)
                printf("%N\n", h.body);
        } catch (hash<ExceptionInfo> ex) {
            if (opt.fullex)
                printf("%s\n", get_exception_string(ex));
            else {
                if (ex.err == "DESERIALIZATION-ERROR" && info."response-headers"."content-type" == "text/html")
                    printf("%s\n%s\n", info."response-uri", html_decode(info."response-body"));
                else {
                    printf("%s: %s: %s", rc.getURL(), ex.err, ex.desc);
                    if (ex.arg) {
                        print(": ");
                        if (ex.arg.body.typeCode() == NT_STRING) {
                            trim ex.arg.body;
                            print(ex.arg.body);
                        } else {
                            if (ex.arg.typeCode() == NT_STRING) {
                                trim ex.arg;
                                printf("%y", ex.arg);
                            } else
                                printf("%y", ex.arg);
                        }
                    }
                    print("\n");
                }
            }
        }
    }

    static error(string fmt) {
        stderr.printf("%s: ERROR: %s\n", get_script_name(), vsprintf(fmt, argv));
        exit(1);
    }

    private showRestRequest(hash info, any args, *hash opt) {
        printf("> %s\n", info."request-uri");
        if (opt.lit > 1)
            printf("> %N\n", info.headers);
        if (info."request-body") {
            *string str;
            if (opt.reformat) {
                switch (info."request-serialization") {
%ifndef NoXml
                    case "xml": str = make_xmlrpc_value(args, XGF_ADD_FORMATTING); break;
                    case "rawxml": str = make_xml(args, XGF_ADD_FORMATTING); break;
%endif
%ifndef NoJson
                    case "json": str = make_json(args, JGF_ADD_FORMATTING); break;
%endif
%ifndef NoYaml
                    case "yaml": str = trim(make_yaml(args, YAML::BlockStyle)); break;
%endif
                    case "url": str = mime_get_form_urlencoded_string(args); break;
                    default: str = getBody(info); break;
                }
            }
            else
                str = getBody(info);
            printf("> %s\n", str);
        }
    }

    private showRestResponse(hash info, any rv, *hash opt) {
        if (!info."response-uri")
            return;
        printf("< %s\n", info."response-uri");
        if (opt.lit > 1)
            printf("< %N\n", info."response-headers" - "body");
        if (info."response-body") {
            if (!exists rv)
                rv = info."response-body";
            string str;
            switch (info."response-serialization") {
%ifndef NoXml
                case "xml": str = make_xmlrpc_value(rv, opt.reformat ? XGF_ADD_FORMATTING : NOTHING); break;
                case "rawxml": str = make_xml(rv, opt.reformat ? XGF_ADD_FORMATTING : NOTHING); break;
%endif
%ifndef NoJson
                case "json": str = make_json(rv, opt.reformat ? JGF_ADD_FORMATTING : NOTHING); break;
%endif
%ifndef NoYaml
                case "yaml": str = trim(make_yaml(rv, opt.reformat ? YAML::BlockStyle : NOTHING)); break;
%endif
                case "url": str = mime_get_form_urlencoded_string(rv); break;
                default: str = trim(info."response-body"); break;
            }
            printf("< %s\n", str);
        }
    }

    private string getBody(hash info) {
        switch (info.headers."Content-Encoding") {
            case "deflate":
            case "x-deflate":
                info."request-body" = uncompress_to_string(info."request-body");
                break;
            case "gzip":
            case "x-gzip":
                info."request-body" = gunzip_to_string(info."request-body");
                break;
            case "bzip2":
            case "x-bzip2":
                info."request-body" = bunzip2_to_string(info."request-body");
                break;
            case "identity":
                info."request-body" = binary_to_string(info."request-body");
                break;
            case NOTHING:
                break;
            default:
                throw "UNKNOWN-CONTENT-ENCODING", sprintf("unknown Content-Encoding %y used to send message", info.headers."Content-Encoding");
        }
        return trim(info."request-body");
    }

    usage() {
        printf("usage: %s [options] [get|patch|post|delete] path|URL ['qore msg body']
** Required Options (can be set with environment variables as well)
 -c,--connection=ARG           the SAP S/4HANA connection name to use
 -k,--apikey=ARG               the API key (or from $SAP_APIKEY)
 -i,--client-id=ARG            the SAP OAuth2 client ID (or from $SAP_CLIENT_ID)
 -s,--client-secret=ARG        the API OAuth2 client secret (or from $SAP_CLIENT_SECRET)

** Other Options
 -e,--send-encoding[=ARG]      set compression in outgoing request
                               [ARG=gzip,deflate,bzip2,identity]
 -E,--full-exception           show full exception output
 -H,--header=ARG               send header with request
 -P,--proxy-url=ARG            set the proxy URL (ex: http://user:pass@proxy:port)
 -l,--literal                  show literal API calls (more l's, more info)
 -R,--reformat                 reformat data with -l+ for better readability
 -S,--serialization=ARG        set REST data serialization type:
                               auto, json, yaml, xml, rawxml, url
 -t,--timeout=ARG              set HTTP timeout in seconds
 -v,--verbose                  show more information
 -W,--show-url                 show default REST API URL and exit
 -h,--help                     this help text
", get_script_name());
        exit(1);
    }

}
