[
  {
    "path": ".github/workflows/ci.yml",
    "content": "---\nname: build\non:\n  push:\n    branches:\n      - master\n  pull_request:\n    branches:\n      - master\njobs:\n  ci:\n    name: Run checks and tests over ${{matrix.otp}} and ${{matrix.os}}\n    runs-on: ${{matrix.os}}\n    strategy:\n      matrix:\n        otp: ['25.0', '26.0', '27.0']\n        os: [ubuntu-latest]\n    steps:\n      - uses: actions/checkout@v4\n      - uses: erlef/setup-beam@v1\n        with:\n          otp-version: ${{matrix.otp}}\n          rebar3-version: '3.24.0'\n      - run: rebar3 compile\n      - run: rebar3 xref\n      - run: rebar3 efmt -c\n      - run: rebar3 eunit\n      - run: rebar3 dialyzer\n      - run: rebar3 edoc\n"
  },
  {
    "path": ".gitignore",
    "content": ".eunit\ndeps\n*.o\n*.beam\n*.plt\nerl_crash.dump\nebin/*.beam\nrel/example_project\n.concrete/DEV_MODE\n.rebar\n*~\n_build\nrebar.lock\nrebar3.crashdump\ndoc/*\n!doc/overview.edoc\n.DS_Store"
  },
  {
    "path": "Dockerfile",
    "content": "# docker image build -t cfl:latest .\n# docker container run -it cfl:latest\n\nFROM alpine:3.17.2\nLABEL maintainer=\"Jörgen Brandt <joergen@cuneiform-lang.org>\"\n\nENV BIN_PATH /usr/local/bin\n\nWORKDIR /tmp\nRUN apk add --update git erlang erlang-dev erlang-dialyzer\nRUN git clone https://github.com/erlang/rebar3.git && (cd rebar3 && ./bootstrap) && cp rebar3/rebar3 $BIN_PATH && rm -rf rebar3\nRUN git clone https://github.com/joergen7/cuneiform.git && (cd cuneiform && rebar3 escriptize) && cp cuneiform/_build/default/bin/cfl $BIN_PATH && rm -rf cuneiform\nRUN git clone https://github.com/joergen7/cre.git && (cd cre && rebar3 escriptize) && cp cre/_build/default/bin/cre $BIN_PATH && rm -rf cre\nRUN git clone https://github.com/joergen7/cf_client.git && (cd cf_client && rebar3 escriptize) && cp cf_client/_build/default/bin/cfl_client $BIN_PATH && rm -rf cf_client\nRUN git clone https://github.com/joergen7/cf_worker.git && (cd cf_worker && rebar3 escriptize) && cp cf_worker/_build/default/bin/cfl_wrk $BIN_PATH && rm -rf cf_worker\nRUN git clone https://github.com/joergen7/effi.git && (cd effi && rebar3 escriptize) && cp effi/_build/default/bin/effi $BIN_PATH && rm -rf effi\n\n# foreign languages\nRUN apk add nodejs octave racket bash elixir gnuplot openjdk17 python3 R R-dev R-doc perl \n# Wal\nRUN apk add py3-pip cmake g++ python3-dev && pip install build && git clone https://github.com/ics-jku/wal.git && (cd wal && git checkout 1ffa6a3 && make install) && rm -rf wal\n\nRUN echo '$y$j9T$7rB03tCGBZHKyQPR/jata1$UF9ICbyarE/Vs3s2paRKnIA8mP6ayA0mlog/KSSPMvD' > /root/.erlang.cookie && chmod 400 /root/.erlang.cookie\n\nCMD [\"sh\"]"
  },
  {
    "path": "LICENSE",
    "content": "Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: How to apply the Apache License to your work.\n\n      To apply the Apache License to your work, attach the following\n      boilerplate notice, with the fields enclosed by brackets \"{}\"\n      replaced with your own identifying information. (Don't include\n      the brackets!)  The text should be enclosed in the appropriate\n      comment syntax for the file format. We also recommend that a\n      file or class name and description of purpose be included on the\n      same \"printed page\" as the copyright notice for easier\n      identification within third-party archives.\n\n   Copyright 2013 Jörgen Brandt <joergen@cuneiform-lang.org>\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License."
  },
  {
    "path": "README.md",
    "content": "![Cuneiform: Data analysis open and general](priv/cuneiform_title.jpg)\n\n[![hex.pm](https://img.shields.io/hexpm/v/cuneiform.svg?style=flat-square)](https://hex.pm/packages/cuneiform)\n\nCuneiform is a large-scale data analysis functional programming language. It is *open* because it easily integrates foreign tools and libraries, e.g., Python libraries or command line tools. It is *general* because it has the expressive power of a functional programming language while using the independence of sub-expressions to automatically parallelize programs. Cuneiform uses distributed Erlang to scalably run in cluster and cloud environments.\n\n[cuneiform-lang.org](https://www.cuneiform-lang.org/)\n\n## Usage\n\n### Compiling\n\nHaving rebar3 available on your system, compile the project by entering\n\n    rebar3 escriptize\n\n### Displaying Cuneiform Help\n\nCompiling the Cuneiform client using `rebar3 escriptize` creates an Erlang script file `_build/default/bin/cfl` which allows starting Cuneiform via the command line. \n\nTo display a help text enter\n\n    _build/default/bin/cfl --help\n\n\nThis will show the command line synopsis, which looks like the following:\n\n    Usage: cfl [-v] [-h] [-n <n_wrk>] [-w <wrk_dir>] [-r <repo_dir>]\n               [-d <data_dir>]\n\n      -v, --version   Show cf_worker version.\n      -h, --help      Show command line options.\n      -n, --n_wrk     Number of worker processes to start. 0 means auto-detect \n                      available processors.\n      -w, --wrk_dir   Working directory in which workers store temporary files.\n      -r, --repo_dir  Repository directory for intermediate and output data.\n      -d, --data_dir  Data directory where input data is located.\n\nThis script is self-contained and can be moved around to, e.g., `~/bin/cfl`. From here on we assume that the `cfl` script is accessible in your system path and that we can start it by just entering `cfl` instead of `_build/default/bin/cfl`.\n\n\n#### Starting an Interactive Shell\n\nYou can start a shell and program Cuneiform interactively by starting it without any command line parameters like so:\n\n    cfl\n\nThis will open a shell giving the following initial output, along with a number of status messages:\n\n               @@WB      Cuneiform\n              @@E_____\n         _g@@@@@WWWWWWL  Type help for usage info\n       g@@#*`3@B              quit to exit shell\n      @@P    3@B\n      @N____ 3@B         http://www.cuneiform-lang.org\n      \"W@@@WF3@B         Jorgen Brandt\n\n    1>\n\nNote that starting Cuneiform like that will create a local instance of a Cuneiform that entails the scheduler service, a client service, and as many worker services as CPUs were detected on the host machine. To set up a distributed Cuneiform system, these services need to be started separately on multiple hosts as needed.\n\n\n#### Running a Cuneiform Script\n\nAlternatively, Cuneiform can be started by giving it a source file which will only output the final result of the computation. If your Cuneiform script is stored in `my_script.cfl` start it by entering\n\n    cfl my_script.cfl\n\n## Examples\n\nA collection of self-contained Cuneiform examples is available under [joergen7/cuneiform-examples](https://github.com/joergen7/cuneiform-examples).\n\n### Variable assignment\n\nYou can assign a value to a variable and retrieve a variable's content like so:\n\n    let x : Str =\n      \"foo\";\n\n    x;\n\nIn the first line we assign the value `\"foo\"` to a variable named `x` declaring its type to be `Str`. In the last line we query the variable `x`.\n\n### Booleans and Conditions\n\nWe can branch execution based on conditions using conditional statements. Conditionals are expressions.\n\n    let x : Str =\n      if true\n      then\n        \"bla\"\n      else\n        \"blub\"\n      end;\n\n    x;\n\nThe above command the conditional binding the string `\"bla\"` to the variable `x`. Then, we query the variable.\n\n### Lists\n\nWe can construct list literals by enumerating their elements in square brackets and declaring the type of the list elements.\n\n    let xs : [Bool] =\n      [true, false, true, true : Bool];\n\n    xs;\n\nHere, we define the list `xs` whose elements are of type `Bool` giving four Boolean values of which only the second is `false`.\n\n### Records and Pattern Matching\n\nA record is a collection of fields that can be accessed via their labels. Literal records can be constructed like so:\n\n    let r : <a : Str, b : Bool> =\n      <a = \"blub\", b = false>;\n\n    ( r|a );\n\nWe define a record `r` with two fields `a` and `b`, of types `Str` and `Bool` respectively. The field associated with `a` gets the value `\"blub\"` while the field associated with `b` gets the value `false`. In the last line we access the `a` field of the record `r`.\n\nAlternatively, we can access record fields via pattern matching:\n\n    let <a = z : Str> = r;\n    z;\n\nIn the first line we associate the variable `z` with the field `a` of record `r`. In the second line we query the content of `z`.\n\n### Native Function Definition\n\nDefining native functions in Cuneiform is done by giving the function name, its signature, and a body expression in curly braces:\n\n    def identity( x : Str ) -> Str {\n      x\n    }\n\n    identity( x = \"bar\" );\n\nIn the first line we define the function `identity` which consumes an argument `x` of type `Str` and produces a return value of type `Str`. In the second line, the body expression is just the argument `x`. In the last line we call the function binding the argument `x` to the value `\"bar\"`.\n\n### Foreign Function Definition\n\nDefining foreign functions is done by giving the function name, its signature, the foreign language name, and the function body in mickey-mouse-eared curly braces.\n\n    def greet( person : Str ) -> <out : Str> in Bash *{\n      out=\"Hello $person\"\n    }*\n\n    greet( person = \"Peter\" );\n\nThe first line defines a foreign function `greet` taking one argument `person` of type `Str` and returning a tuple with a single field `out` of type `Str`. The foreign function body is given in Bash code. In the last line we call the foreign function, binding the argument `person` to the string value `\"Peter\"`.\n\n### Iterating over Lists using For\n\nTo perform an operation on each element of a list, one can iterate using for:\n\n    let xs : [Bool] =\n      [true, false, true, true : Bool];\n\n    for x : Bool <- xs do\n      not x\n      : Bool\n    end;\n\nHere, we define a list of four Booleans and negate each element.\n\n### Aggregating Lists using Fold\n\nWe can aggregate over lists using fold:\n\n    def add( a : Str, b : Str ) -> <c : Str> in Python *{\n      c = int( a )+int( b )\n    }*\n\n    let xs : [Str] = [1, 2, 3 : Str];\n\n    let sum : Str =\n      fold acc : Str = 0, x : Str <- xs do\n        ( add( a = acc, b = x )|c )\n      end;\n\n    sum;\n\nHere, we first define the function `add` which lets us add two numbers in Python and then the string list `xs` containing the numbers from one to three. We aggregate the sum of the numbers in `xs` and store it the result in the variable `sum`. Lastly, we query the `sum` variable.\n\n## System Requirements\n\n- [Erlang](https://www.erlang.org) OTP 19.0 or higher\n- [Rebar3](https://www.rebar3.org) 3.0.0 or higher\n\n## Resources\n\n- [cuneiform-lang.org](https://www.cuneiform-lang.org/). Official website of the Cuneiform programming language.\n- [joergen7/cuneiform-examples](https://github.com/joergen7/cuneiform-examples). Collection of small, self-contained Cuneiform code examples.\n- [joergen7/cre](https://github.com/joergen7/cre). A common runtime environment (CRE) for distributed workflow languages.\n- [joergen7/cf_client](https://github.com/joergen7/cf_client). A Cuneiform client implementation.\n- [joergen7/cf_worker](https://github.com/joergen7/cf_worker). A Cuneiform worker implementation.\n\n## License\n\n[Apache 2.0](https://www.apache.org/licenses/LICENSE-2.0.html)\n"
  },
  {
    "path": "docker-compose.yml",
    "content": "services:\n  cre:\n    build: .\n    command: cre\n    networks:\n      - cuneiform-net\n    hostname: cre_host    # the worker connects to cre@[hostname]\n\n  cfl_wrk:\n    build: .\n    command: cfl_wrk -c cre@cre_host -w /tmp/_cuneiform/wrk -r /opt/_cuneiform/repo -d /opt/_cuneiform/data\n    volumes:\n      - type: volume\n        source: repo-vol\n        target: /opt/_cuneiform/repo\n      - type: volume\n        source: data-vol\n        target: /opt/_cuneiform/data\n        read_only: true\n    networks:\n      - cuneiform-net\n    depends_on:\n      - cre\n    deploy:\n      mode: replicated\n      replicas: 2         # 2 replicas\n    cpus: 4               # each with 4 cores makes 8 worker processes\n\n  cfl_client:             # the cfl_client process starts a Cuneiform shell and then immediately exits\n    build: .\n    command: cfl_client -c cre@cre_host\n    networks:\n      - cuneiform-net\n    depends_on:\n      - cre\n\n\nnetworks:\n  cuneiform-net:\n\nvolumes:\n  repo-vol:\n  data-vol:\n\n"
  },
  {
    "path": "priv/cf_script",
    "content": "#!/usr/bin/env bash\n#\n# cuneiform\n#\n# Copyright 2013 Jörgen Brandt\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# -------------------------------------------------------------------\n\nset -eu -o pipefail\n\nSCRIPT=`mktemp`\ncat /dev/stdin > $SCRIPT\n\ncuneiform $@ $SCRIPT\n"
  },
  {
    "path": "rebar.config",
    "content": "{erl_opts, [debug_info]}.\n\n{deps, [{cf_client, {git, \"https://github.com/joergen7/cf_client.git\", {branch, \"master\"}}},\n        {cf_worker, {git, \"https://github.com/joergen7/cf_worker.git\", {branch, \"master\"}}},\n        {cre, {git, \"https://github.com/joergen7/cre.git\", {branch, \"master\"}}},\n        {lib_conf, {git, \"https://github.com/joergen7/lib_conf.git\", {branch, \"master\"}}},\n        {getopt, \"1.0.3\"}]}.\n\n{escript_incl_apps, [cf_client, cf_worker, cre, effi, gen_pnet, getopt,\n                     jsone, lib_combin, lib_conf]}.\n\n{escript_name, \"cfl\"}.\n\n{profiles,\n [{test, [{cover_enabled, true}]}]}.\n\n{dialyzer, [{warnings, [unmatched_returns,\n                        error_handling,\n                        underspecs]},\n            {plt_extra_apps, [cf_client, cf_worker, cre, getopt]}]}.\n\n{xref_checks, [undefined_function_calls,\n               undefined_functions,\n               locals_not_used,\n               deprecated_function_calls,\n               deprecated_functions]}.\n\n{project_plugins, [rebar3_efmt]}.\n"
  },
  {
    "path": "src/cuneiform.app.src",
    "content": "{application, cuneiform,\n [{description, \"A functional workflow language for large-scale scientific data analysis.\"},\n  {vsn, \"3.0.6\"},\n  {registered, []},\n  {applications, [kernel,\n                  stdlib]},\n  {env, []},\n  {modules, [cuneiform]},\n  {maintainers, [\"Jorgen Brandt\"]},\n  {licenses, [\"Apache 2.0\"]},\n  {links, [{\"GitHub\", \"https://github.com/joergen7/cuneiform/\"}]}]}.\n"
  },
  {
    "path": "src/cuneiform.erl",
    "content": "%% -*- erlang -*-\n%%\n%% Cuneiform distributed programming language\n%%\n%% Copyright 2013 Jörgen Brandt <joergen@cuneiform-lang.org>\n%%\n%% Licensed under the Apache License, Version 2.0 (the \"License\");\n%% you may not use this file except in compliance with the License.\n%% You may obtain a copy of the License at\n%%\n%%     http://www.apache.org/licenses/LICENSE-2.0\n%%\n%% Unless required by applicable law or agreed to in writing, software\n%% distributed under the License is distributed on an \"AS IS\" BASIS,\n%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n%% See the License for the specific language governing permissions and\n%% limitations under the License.\n%%\n%% -------------------------------------------------------------------\n%% @author Jörgen Brandt <joergen.brandt@onlinehome.de>\n%% @version 3.0.6\n%% @copyright 2013\n%%\n%%\n%%\n%%\n%%\n%% @end\n%% -------------------------------------------------------------------\n\n-module(cuneiform).\n\n-export([main/1]).\n\n-define(VSN, \"3.0.6\").\n\n%%====================================================================\n%% Escript main function\n%%====================================================================\n\n\nmain(Args) ->\n\n    % TODO: neutralize all configurations\n\n    try\n\n        case getopt:parse(get_optspec_lst(), Args) of\n\n            {error, R1} ->\n                throw({error, R1});\n\n            {ok, {OptLst, NonOptLst}} ->\n\n                % break if version needs to be displayed\n                case lists:member(version, OptLst) of\n                    false -> ok;\n                    true -> throw(version)\n                end,\n\n                % break if help needs to be displayed\n                case lists:member(help, OptLst) of\n                    false -> ok;\n                    true -> throw(help)\n                end,\n\n                % extract number of workers\n                M1 =\n                    case lists:keyfind(n_wrk, 1, OptLst) of\n                        false -> #{n_wrk => <<\"auto\">>};\n                        {n_wrk, N} when N > 0 -> #{n_wrk => N};\n                        A -> throw({error, {invalid_arg, A}})\n                    end,\n\n                % extract working directory\n                M2 =\n                    case lists:keyfind(wrk_dir, 1, OptLst) of\n                        false -> M1#{wrk_dir => <<\"./_cuneiform/wrk\">>};\n                        {wrk_dir, W} -> M1#{wrk_dir => W}\n                    end,\n\n                % extract repository directory\n                M3 =\n                    case lists:keyfind(repo_dir, 1, OptLst) of\n                        false -> M2#{repo_dir => <<\"./_cuneiform/repo\">>};\n                        {repo_dir, R} -> M2#{repo_dir => R}\n                    end,\n\n                % extract data directory\n                M4 =\n                    case lists:keyfind(data_dir, 1, OptLst) of\n                        false -> M3#{data_dir => <<\".\">>};\n                        {data_dir, D} -> M3#{data_dir => D}\n                    end,\n\n                % set flag maps\n                ok = application:set_env(cf_client, flag_map, #{cre_node => <<\"node\">>}),\n                ok = application:set_env(cf_worker, flag_map, M4#{cre_node => <<\"node\">>}),\n\n                % start CRE application\n                ok = cre:start(),\n\n                % start worker application\n                ok = cf_worker:start(),\n\n                % start client application\n                ok = cf_client:start(),\n\n                case NonOptLst of\n                    [] -> throw(shell);\n                    [_ | _] -> throw({load, NonOptLst})\n                end\n\n        end\n\n    catch\n\n        throw:version ->\n            print_version();\n\n        throw:help ->\n            print_help();\n\n        throw:shell ->\n            print_version(),\n            ok = cuneiform_shell:shell(cf_client);\n\n        throw:{load, FileLst} ->\n\n            F =\n                fun(File) ->\n\n                        % collect reply list\n                        ReplyLst =\n                            case file:read_file(File) of\n\n                                {error, R3} ->\n                                    io:format(\"we land here~n\"),\n                                    [{error, load, {File, R3}}];\n\n                                {ok, B} ->\n                                    S = binary_to_list(B),\n                                    cuneiform_shell:shell_eval_oneshot(S)\n\n                            end,\n\n                        cuneiform_shell:process_reply_lst(ReplyLst, cf_client, silent)\n\n                end,\n\n            ok = lists:foreach(F, FileLst);\n\n        throw:{error, Reason} ->\n            ReplyLst = [{error, load, Reason}],\n            cuneiform_shell:process_reply_lst(ReplyLst, cf_client, silent)\n\n    end.\n\n\n%%====================================================================\n%% Internal functions\n%%====================================================================\n\n\nget_optspec_lst() ->\n    [{version, $v, \"version\", undefined, \"Show cf_worker version.\"},\n     {help, $h, \"help\", undefined, \"Show command line options.\"},\n     {n_wrk, $n, \"n_wrk\", integer, \"Number of worker processes to start. 0 means auto-detect available processors.\"},\n     {wrk_dir, $w, \"wrk_dir\", binary, \"Working directory in which workers store temporary files.\"},\n     {repo_dir, $r, \"repo_dir\", binary, \"Repository directory for intermediate and output data.\"},\n     {data_dir, $d, \"data_dir\", binary, \"Data directory where input data is located.\"}].\n\n\nprint_help() ->\n    getopt:usage(get_optspec_lst(), \"cfl\").\n\n\nprint_version() ->\n    io:format(\"cuneiform ~s~n\", [?VSN]).\n"
  }
]