[
  {
    "path": ".github/workflows/build-controller.yaml",
    "content": "name: build-controller\n\non:\n  pull_request:\n    branches: main\n  push:\n    branches: main\n    tags:\n      - v*\n\njobs:\n  buildx:\n    runs-on: ubuntu-latest\n    steps:\n      -\n        name: Checkout\n        uses: actions/checkout@v2\n      -\n        name: Prepare\n        id: prepare\n        run: |\n          DOCKER_IMAGE=ghcr.io/paolomainardi/additronk8s-game-controller\n          DOCKER_PLATFORMS=linux/amd64,linux/arm/v7,linux/arm64\n          DOCKERFILE_PATH=./k8s/src/game-controller\n          VERSION=latest\n\n          if [[ $GITHUB_REF == refs/tags/* ]]; then\n            VERSION=${GITHUB_REF#refs/tags/v}\n          fi\n          if [ \"${{ github.event_name }}\" = \"schedule\" ]; then\n            VERSION=nightly\n          fi\n\n          TAGS=\"--tag ${DOCKER_IMAGE}:${VERSION}\"\n          if [[ $VERSION =~ ^[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}$ ]]; then\n            TAGS=\"$TAGS --tag ${DOCKER_IMAGE}:latest\"\n          fi\n\n          echo ::set-output name=docker_image::${DOCKER_IMAGE}\n          echo ::set-output name=version::${VERSION}\n          echo ::set-output name=buildx_args::--platform ${DOCKER_PLATFORMS} \\\n            --build-arg VERSION=${VERSION} \\\n            --build-arg BUILD_DATE=$(date -u +'%Y-%m-%dT%H:%M:%SZ') \\\n            --build-arg VCS_REF=${GITHUB_SHA::8} \\\n            ${TAGS} --file ${DOCKERFILE_PATH}/Dockerfile ${DOCKERFILE_PATH}\n\n      - name: Set up QEMU\n        uses: docker/setup-qemu-action@v1\n\n      - name: Set up Docker Buildx\n        uses: docker/setup-buildx-action@v1\n\n      - name: Docker Buildx (build)\n        run: |\n          docker buildx build --output \"type=image,push=false\" ${{ steps.prepare.outputs.buildx_args }}\n\n      - name: Log into GitHub Container Registry\n        run: echo \"${{ secrets.GITHUB_TOKEN }}\" | docker login https://ghcr.io -u ${{ github.actor }} --password-stdin\n\n      - name: Docker Buildx (push)\n        if: success() && github.event_name != 'pull_request'\n        run: |\n          docker buildx build --output \"type=image,push=true\" ${{ steps.prepare.outputs.buildx_args }}\n\n      - name: Inspect image\n        if: always() && github.event_name != 'pull_request'\n        run: |\n          docker buildx imagetools inspect ${{ steps.prepare.outputs.docker_image }}:${{ steps.prepare.outputs.version }}"
  },
  {
    "path": ".github/workflows/build-engine.yml",
    "content": "name: build-engine\n\non:\n  pull_request:\n    branches: main\n  push:\n    branches: main\n    tags:\n      - v*\n\njobs:\n  buildx:\n    runs-on: ubuntu-latest\n    steps:\n      -\n        name: Checkout\n        uses: actions/checkout@v2\n      -\n        name: Prepare\n        id: prepare\n        run: |\n          DOCKER_IMAGE=ghcr.io/paolomainardi/additronk8s-game-engine\n          DOCKER_PLATFORMS=linux/amd64,linux/arm/v7,linux/arm64\n          DOCKERFILE_PATH=./game-engine\n          VERSION=latest\n\n          if [[ $GITHUB_REF == refs/tags/* ]]; then\n            VERSION=${GITHUB_REF#refs/tags/v}\n          fi\n          if [ \"${{ github.event_name }}\" = \"schedule\" ]; then\n            VERSION=nightly\n          fi\n\n          TAGS=\"--tag ${DOCKER_IMAGE}:${VERSION}\"\n          if [[ $VERSION =~ ^[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}$ ]]; then\n            TAGS=\"$TAGS --tag ${DOCKER_IMAGE}:latest\"\n          fi\n\n          echo ::set-output name=docker_image::${DOCKER_IMAGE}\n          echo ::set-output name=version::${VERSION}\n          echo ::set-output name=buildx_args::--platform ${DOCKER_PLATFORMS} \\\n            --build-arg VERSION=${VERSION} \\\n            --build-arg BUILD_DATE=$(date -u +'%Y-%m-%dT%H:%M:%SZ') \\\n            --build-arg VCS_REF=${GITHUB_SHA::8} \\\n            ${TAGS} --file ${DOCKERFILE_PATH}/Dockerfile ${DOCKERFILE_PATH}\n\n      - name: Set up QEMU\n        uses: docker/setup-qemu-action@v1\n\n      - name: Set up Docker Buildx\n        uses: docker/setup-buildx-action@v1\n\n      - name: Docker Buildx (build)\n        run: |\n          docker buildx build --output \"type=image,push=false\" ${{ steps.prepare.outputs.buildx_args }}\n\n      - name: Log into GitHub Container Registry\n        run: echo \"${{ secrets.GITHUB_TOKEN }}\" | docker login https://ghcr.io -u ${{ github.actor }} --password-stdin\n\n      - name: Docker Buildx (push)\n        if: success() && github.event_name != 'pull_request'\n        run: |\n          docker buildx build --output \"type=image,push=true\" ${{ steps.prepare.outputs.buildx_args }}\n\n      - name: Inspect image\n        if: always() && github.event_name != 'pull_request'\n        run: |\n          docker buildx imagetools inspect ${{ steps.prepare.outputs.docker_image }}:${{ steps.prepare.outputs.version }}"
  },
  {
    "path": ".gitignore",
    "content": "games\nnode_modules\n"
  },
  {
    "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 [yyyy] [name of copyright owner]\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"
  },
  {
    "path": "Makefile",
    "content": "all: run\n\nSHELL := /bin/bash\n\nifndef GAME_DIR\n\tGAME_DIR=MONKEY_FLOPPY\nendif\nifndef GAME_EXE\n\tGAME_EXE=MONEY.EXE\nendif\n\nbuild-game-engine:\n\tdocker build -t ghcr.io/paolomainardi/additronk8s-game-engine:latest game-engine\n\nkind-load-game-engine: build-game-engine\n\tkind load docker-image ghcr.io/paolomainardi/additronk8s-game-engine:latest --name retrogames-k8s-dev\n\nrun-game-engine: build\n\t./game-engine/run.sh\n\nrun: create-kind-cluster kind-load-game-engine\n\tskaffold run -n games --tail\n\ndev: kind-load-game-engine\n\tskaffold dev -n games --tail\n\ncreate-kind-cluster:\n\tkind delete cluster --name retrogames-k8s-dev || true\n\tkind create cluster --name retrogames-k8s-dev\n\n"
  },
  {
    "path": "README.md",
    "content": "# AdditronK8S\n\n[![build-controller](https://github.com/paolomainardi/additronk8s-retrogames-kubernetes-controller/actions/workflows/build-controller.yaml/badge.svg)](https://github.com/paolomainardi/additronk8s-retrogames-kubernetes-controller/actions/workflows/build-controller.yaml) [![build-engine](https://github.com/paolomainardi/additronk8s-retrogames-kubernetes-controller/actions/workflows/build-engine.yml/badge.svg)](https://github.com/paolomainardi/additronk8s-retrogames-kubernetes-controller/actions/workflows/build-engine.yml)\n\n## Description\n\nAdditronK8S is a retro game machine build as a Kubernetes custom controller and\nimplemented in Javascript.\n\n> The name `Additron` is a tribute to the great inventor and scientist [Josef Kates](https://en.wikipedia.org/wiki/Josef_Kates) who invented the [**first digital playing machine**](https://en.wikipedia.org/wiki/Bertie_the_Brain) to showcase his Additron tube invention.\n\nI did this as a PoC [for a company talk](https://www2.slideshare.net/sparkfabrik/retro-gaming-machine-made-with-javascript-and-kubernetes) [(Video)](https://youtu.be/XlhSCWzgQ4k), to demonstrate how **powerful** can be the\n**Kubernetes APIs** when used also to build custom applications.\n\nI chose to use **Javascript** as it is an **officially supported client**\nand also because I didn't find any project a bit more complex than a simple hello world, to implement a custom controller.\n\n> Personal note: When developing for Kubernetes, you have to deal with tons of REST APIs and complex relationship between them, this is where the GO\necosystem shines, you have framework and abstractions used to build Kubernetes\nitself and you are sure to use top-notch quality code; so if you plan\nto implement something serious with Kubernetes, my advice is to use GO as\na first class citizen language of your system.\n\nOne of the goal of this project was to use just **Kubernetes API without any external dependency** (neither the storage),\ninfact is noteworthy that `Configmaps` are (ab)used as a persistent storage layer, using a simple technique\nof split/merge parts of files to save the games.\n\nHow it works (hand written schematic):\n\n![AdditronK8S Scheme](./docs/images/scheme.jpg)\n\nSee it in action:\n\n[![asciicast](https://asciinema.org/a/yuUCC0i5BizfRPYoSBcGAP4Sc.svg)](https://asciinema.org/a/yuUCC0i5BizfRPYoSBcGAP4Sc)\n\nHere you can find the slides of my talk: https://www2.slideshare.net/sparkfabrik/retro-gaming-machine-made-with-javascript-and-kubernetes\n\n## Technology\n\nThis project consists of 3 main components:\n\n1. A Docker image to run games based on Dosbox + [noVNC + Pulseaudio/gStreamer](https://github.com/novnc/noVNC/issues/302)\n2. A Javascript Kubernetes custom controller who implements the CRD and the needed logic to run the games.\n3. A K3d Kubernetes cluster and Skaffold to manage it.\n\n> WARNING: The code is not even close to be production ready, it is just a quick PoC to build a custom controller in Javascript.\n\n## Quick start\n\nYou just need a working k8s cluster, with a working external connection.\n\nTo install it from the root, run the following commands:\n\n```shell\nkubectl apply -f k8s/manifests/namespace.yml\nkubectl -n games apply -f k8s/manifests/crd-game-controller.yml\nkubectl -n games apply -f k8s/manifests/game-controller-sa.yml\nkubectl -n games apply -f k8s/manifests/game-controller-cluster-role.yml\nkubectl -n games apply -f k8s/manifests/game-controller-cluster-role-binding.yml\nkubectl -n games apply -f k8s/manifests/game-controller.yaml\n```\n\nNow you can run a demo game to test if everything is working as expected:\n\n```shell\nkubectl -n games apply -f k8s/games/quake.yml\n```\n\n> You can also tail the logs of the game-controller to ensure that it was successful\n> in processing the location of your game zip file.\n\n> ```shell\n> kubectl -n games logs deployment/game-controller -f\n> ```\n\nOnce you have the game up and running, you can access via the web browser by proxying\nthe game service, like this:\n\n```\nkubectl -n games port-forward svc/quake 8080:8080 8081:8081\n```\n\nFinally you can access the game console on: `https://localhost:8080`\n\nAt this stage you will be presented with the dosbox command line and\nthe command to run to execute the game.\n\n> *IMPORTANT*: To start the audio websocket, before to start the game and inside the\n> dosbox cli, you have to press `ALT + s` this will start once the needed websocket,\n> to transport the audio from the pulseaudio server to your browser.\n\n## Games\n\nFiles can be downloaded from any public http endpoint or from any public GCP cloud storage bucket.\n\nThe expect manifest to run a game is this:\n\n```yaml\napiVersion: retro.sparkfabrik.com/v1\nkind: Game\nmetadata:\n  name: game-name\nspec:\n  name: \"Game name human friendly\"\n  zipUrl: \"gs://my-gs-bucket/game.zip\"\n  dir: \"GAME\"\n  exe: \"GAME.EXE\"\n```\n\nWhere `dir` represent the directory of the unzipped game and `exe` the binary to run.\n\nTo be clear, this is a structure we expect:\n\n```\nunzip game.zip\n\n> GAME\n - GAME.EXE\n - SOUND.MOD\n - VIDEO.MOD\n```\n\n### Development\n\nThe development environment is based on `k3d` and `skaffold`,\nby running `make dev` you will have end up with:\n\n1. A k3d kubernetes cluster\n2. Docker images loaded into the k3d cluster\n3. Game controller up and running with live-reload in case of code changes\n\n## References\n\n* [Retro DOS Games on Kubernetes:](https://www.virtuallyghetto.com/2021/02/retro-dos-games-on-kubernetes.html) many thanks to [William Lam](https://twitter.com/lamw) for this great write-up.\n"
  },
  {
    "path": "game-engine/.dockerignore",
    "content": "games"
  },
  {
    "path": "game-engine/Dockerfile",
    "content": "FROM debian:10.7\n\nENV LANG=en_US.UTF-8 LANGUAGE=en_US.UTF-8 LC_ALL=C.UTF-8 DISPLAY=:0.0\n\n# Install dependencies.\nRUN apt-get update \\\n     && DEBIAN_FRONTEND=noninteractive apt-get install --yes --no-install-recommends \\\n     bzip2 \\\n     gstreamer1.0-plugins-good \\\n     gstreamer1.0-pulseaudio \\\n     gstreamer1.0-tools \\\n     libglu1-mesa \\\n     libgtk2.0-0 \\\n     libncursesw5 \\\n     libopenal1 \\\n     libsdl-image1.2 \\\n     libsdl-ttf2.0-0 \\\n     libsdl1.2debian \\\n     libsndfile1 \\\n     novnc \\\n     pulseaudio \\\n     supervisor \\\n     ucspi-tcp \\\n     wget \\\n     x11vnc \\\n     xvfb \\\n     dosbox \\\n     procps \\\n     gettext-base \\\n     unzip \\\n     patch \\\n     && rm -rf /var/lib/apt/lists/*\n\n# Configure pulseaudio.\nCOPY conf/default.pa conf/client.conf /etc/pulse/\n\n# Force vnc_lite.html to be used for novnc, to avoid having the directory listing page.\n# Additionally, turn off the control bar. Finally, add a hook to start audio.\nCOPY conf/webaudio.js /usr/share/novnc/core/\nCOPY conf/novnc/vnc_lite.html /usr/share/novnc/vnc_lite.html\nRUN ln -s /usr/share/novnc/vnc_lite.html /usr/share/novnc/index.html\n\n# Add a patch to make the background customizable.\nCOPY conf/novnc/background_patch.diff /usr/share/novnc\nRUN  cd /usr/share/novnc && \\\n     patch -p1 < background_patch.diff\n\n# Configure supervisord.\nCOPY conf/supervisord.conf /etc/supervisor/supervisord.conf\n\n# Run everything as standard user/group retrogames.\nRUN groupadd retrogames \\\n     && useradd --create-home --gid retrogames retrogames\nWORKDIR /home/retrogames\n\n# Copy dosbox custom confs.\nCOPY conf/dosbox /dosbox/\nCOPY entrypoint.sh /entrypoint.sh\nRUN chmod +x /entrypoint.sh\n\n# Copy games.\nRUN mkdir /games && chown -R retrogames:retrogames /games\nUSER retrogames\n#COPY --chown=retrogames:retrogames games /games\n\nHEALTHCHECK CMD ps aux | grep dosbox | grep -v grep || exit 1\nENTRYPOINT [ \"supervisord\", \"-c\", \"/etc/supervisor/supervisord.conf\" ]"
  },
  {
    "path": "game-engine/conf/client.conf",
    "content": "default-server=unix:/tmp/pulseaudio.socket\n"
  },
  {
    "path": "game-engine/conf/default.pa",
    "content": "#!/usr/bin/pulseaudio -nF\nload-module module-native-protocol-unix socket=/tmp/pulseaudio.socket auth-anonymous=1\nload-module module-always-sink\n"
  },
  {
    "path": "game-engine/conf/dosbox/dosbox.cli.conf.template",
    "content": "set border 0\nexec dosbox -conf ~/.dosbox/dosbox.conf -fullscreen\nroot@9fb8fc07e1da:~# cat .dosbox/dosbox.conf\n# This is the configurationfile for DOSBox 0.74. (Please use the latest version of DOSBox)\n# Lines starting with a # are commentlines and are ignored by DOSBox.\n# They are used to (briefly) document the effect of each option.\n\n[sdl]\n#       fullscreen: Start dosbox directly in fullscreen. (Press ALT-Enter to go back)\n#       fulldouble: Use double buffering in fullscreen. It can reduce screen flickering, but it can also result in a slow DOSBox.\n#   fullresolution: What resolution to use for fullscreen: original or fixed size (e.g. 1024x768).\n#                     Using your monitor's native resolution with aspect=true might give the best results.\n#                     If you end up with small window on a large screen, try an output different from surface.\n# windowresolution: Scale the window to this size IF the output device supports hardware scaling.\n#                     (output=surface does not!)\n#           output: What video system to use for output.\n#                   Possible values: surface, overlay, opengl, openglnb.\n#         autolock: Mouse will automatically lock, if you click on the screen. (Press CTRL-F10 to unlock)\n#      sensitivity: Mouse sensitivity.\n#      waitonerror: Wait before closing the console if dosbox has an error.\n#         priority: Priority levels for dosbox. Second entry behind the comma is for when dosbox is not focused/minimized.\n#                     pause is only valid for the second entry.\n#                   Possible values: lowest, lower, normal, higher, highest, pause.\n#       mapperfile: File used to load/save the key/event mappings from. Resetmapper only works with the defaul value.\n#     usescancodes: Avoid usage of symkeys, might not work on all operating systems.\n\nfullscreen=true\nfulldouble=false\nfullresolution=0x0\nwindowresolution=0x0\noutput=opengl\nautolock=true\nsensitivity=100\nwaitonerror=true\npriority=higher,normal\nmapperfile=mapper-0.74.map\nusescancodes=false\n\n[dosbox]\n# language: Select another language file.\n#  machine: The type of machine tries to emulate.\n#           Possible values: hercules, cga, tandy, pcjr, ega, vgaonly, svga_s3, svga_et3000, svga_et4000, svga_paradise, vesa_nolfb, vesa_oldvbe.\n# captures: Directory where things like wave, midi, screenshot get captured.\n#  memsize: Amount of memory DOSBox has in megabytes.\n#             This value is best left at its default to avoid problems with some games,\n#             though few games might require a higher value.\n#             There is generally no speed advantage when raising this value.\n\nlanguage=\nmachine=svga_s3\ncaptures=capture\nmemsize=16\n\n[render]\n# frameskip: How many frames DOSBox skips before drawing one.\n#    aspect: Do aspect correction, if your output method doesn't support scaling this can slow things down!.\n#    scaler: Scaler used to enlarge/enhance low resolution modes.\n#              If 'forced' is appended, then the scaler will be used even if the result might not be desired.\n#            Possible values: none, normal2x, normal3x, advmame2x, advmame3x, advinterp2x, advinterp3x, hq2x, hq3x, 2xsai, super2xsai, supereagle, tv2x, tv3x, rgb2x, rgb3x, scan2x, scan3x.\n\nframeskip=0\naspect=false\nscaler=none\n\n[cpu]\n#      core: CPU Core used in emulation. auto will switch to dynamic if available and appropriate.\n#            Possible values: auto, dynamic, normal, simple.\n#   cputype: CPU Type used in emulation. auto is the fastest choice.\n#            Possible values: auto, 386, 386_slow, 486_slow, pentium_slow, 386_prefetch.\n#    cycles: Amount of instructions DOSBox tries to emulate each millisecond.\n#            Setting this value too high results in sound dropouts and lags.\n#            Cycles can be set in 3 ways:\n#              'auto'          tries to guess what a game needs.\n#                              It usually works, but can fail for certain games.\n#              'fixed #number' will set a fixed amount of cycles. This is what you usually need if 'auto' fails.\n#                              (Example: fixed 4000).\n#              'max'           will allocate as much cycles as your computer is able to handle.\n#\n#            Possible values: auto, fixed, max.\n#   cycleup: Amount of cycles to decrease/increase with keycombo.(CTRL-F11/CTRL-F12)\n# cycledown: Setting it lower than 100 will be a percentage.\n\ncore=auto\ncputype=auto\ncycles=auto\ncycleup=10\ncycledown=20\n\n[mixer]\n#   nosound: Enable silent mode, sound is still emulated though.\n#      rate: Mixer sample rate, setting any device's rate higher than this will probably lower their sound quality.\n#            Possible values: 44100, 48000, 32000, 22050, 16000, 11025, 8000, 49716.\n# blocksize: Mixer block size, larger blocks might help sound stuttering but sound will also be more lagged.\n#            Possible values: 1024, 2048, 4096, 8192, 512, 256.\n# prebuffer: How many milliseconds of data to keep on top of the blocksize.\n\nnosound=false\nrate=44100\nblocksize=1024\nprebuffer=20\n\n[midi]\n#     mpu401: Type of MPU-401 to emulate.\n#             Possible values: intelligent, uart, none.\n# mididevice: Device that will receive the MIDI data from MPU-401.\n#             Possible values: default, win32, alsa, oss, coreaudio, coremidi, none.\n# midiconfig: Special configuration options for the device driver. This is usually the id of the device you want to use.\n#               See the README/Manual for more details.\n\nmpu401=intelligent\nmididevice=default\nmidiconfig=\n\n[sblaster]\n#  sbtype: Type of Soundblaster to emulate. gb is Gameblaster.\n#          Possible values: sb1, sb2, sbpro1, sbpro2, sb16, gb, none.\n#  sbbase: The IO address of the soundblaster.\n#          Possible values: 220, 240, 260, 280, 2a0, 2c0, 2e0, 300.\n#     irq: The IRQ number of the soundblaster.\n#          Possible values: 7, 5, 3, 9, 10, 11, 12.\n#     dma: The DMA number of the soundblaster.\n#          Possible values: 1, 5, 0, 3, 6, 7.\n#    hdma: The High DMA number of the soundblaster.\n#          Possible values: 1, 5, 0, 3, 6, 7.\n# sbmixer: Allow the soundblaster mixer to modify the DOSBox mixer.\n# oplmode: Type of OPL emulation. On 'auto' the mode is determined by sblaster type. All OPL modes are Adlib-compatible, except for 'cms'.\n#          Possible values: auto, cms, opl2, dualopl2, opl3, none.\n#  oplemu: Provider for the OPL emulation. compat might provide better quality (see oplrate as well).\n#          Possible values: default, compat, fast.\n# oplrate: Sample rate of OPL music emulation. Use 49716 for highest quality (set the mixer rate accordingly).\n#          Possible values: 44100, 49716, 48000, 32000, 22050, 16000, 11025, 8000.\n\nsbtype=sb16\nsbbase=220\nirq=7\ndma=1\nhdma=5\nsbmixer=true\noplmode=auto\noplemu=default\noplrate=44100\n\n[gus]\n#      gus: Enable the Gravis Ultrasound emulation.\n#  gusrate: Sample rate of Ultrasound emulation.\n#           Possible values: 44100, 48000, 32000, 22050, 16000, 11025, 8000, 49716.\n#  gusbase: The IO base address of the Gravis Ultrasound.\n#           Possible values: 240, 220, 260, 280, 2a0, 2c0, 2e0, 300.\n#   gusirq: The IRQ number of the Gravis Ultrasound.\n#           Possible values: 5, 3, 7, 9, 10, 11, 12.\n#   gusdma: The DMA channel of the Gravis Ultrasound.\n#           Possible values: 3, 0, 1, 5, 6, 7.\n# ultradir: Path to Ultrasound directory. In this directory\n#           there should be a MIDI directory that contains\n#           the patch files for GUS playback. Patch sets used\n#           with Timidity should work fine.\n\ngus=false\ngusrate=44100\ngusbase=240\ngusirq=5\ngusdma=3\nultradir=C:\\ULTRASND\n\n[speaker]\n# pcspeaker: Enable PC-Speaker emulation.\n#    pcrate: Sample rate of the PC-Speaker sound generation.\n#            Possible values: 44100, 48000, 32000, 22050, 16000, 11025, 8000, 49716.\n#     tandy: Enable Tandy Sound System emulation. For 'auto', emulation is present only if machine is set to 'tandy'.\n#            Possible values: auto, on, off.\n# tandyrate: Sample rate of the Tandy 3-Voice generation.\n#            Possible values: 44100, 48000, 32000, 22050, 16000, 11025, 8000, 49716.\n#    disney: Enable Disney Sound Source emulation. (Covox Voice Master and Speech Thing compatible).\n\npcspeaker=true\npcrate=44100\ntandy=auto\ntandyrate=44100\ndisney=true\n\n[joystick]\n# joysticktype: Type of joystick to emulate: auto (default), none,\n#               2axis (supports two joysticks),\n#               4axis (supports one joystick, first joystick used),\n#               4axis_2 (supports one joystick, second joystick used),\n#               fcs (Thrustmaster), ch (CH Flightstick).\n#               none disables joystick emulation.\n#               auto chooses emulation depending on real joystick(s).\n#               (Remember to reset dosbox's mapperfile if you saved it earlier)\n#               Possible values: auto, 2axis, 4axis, 4axis_2, fcs, ch, none.\n#        timed: enable timed intervals for axis. Experiment with this option, if your joystick drifts (away).\n#     autofire: continuously fires as long as you keep the button pressed.\n#       swap34: swap the 3rd and the 4th axis. can be useful for certain joysticks.\n#   buttonwrap: enable button wrapping at the number of emulated buttons.\n\njoysticktype=auto\ntimed=true\nautofire=false\nswap34=false\nbuttonwrap=false\n\n[serial]\n# serial1: set type of device connected to com port.\n#          Can be disabled, dummy, modem, nullmodem, directserial.\n#          Additional parameters must be in the same line in the form of\n#          parameter:value. Parameter for all types is irq (optional).\n#          for directserial: realport (required), rxdelay (optional).\n#                           (realport:COM1 realport:ttyS0).\n#          for modem: listenport (optional).\n#          for nullmodem: server, rxdelay, txdelay, telnet, usedtr,\n#                         transparent, port, inhsocket (all optional).\n#          Example: serial1=modem listenport:5000\n#          Possible values: dummy, disabled, modem, nullmodem, directserial.\n# serial2: see serial1\n#          Possible values: dummy, disabled, modem, nullmodem, directserial.\n# serial3: see serial1\n#          Possible values: dummy, disabled, modem, nullmodem, directserial.\n# serial4: see serial1\n#          Possible values: dummy, disabled, modem, nullmodem, directserial.\n\nserial1=dummy\nserial2=dummy\nserial3=disabled\nserial4=disabled\n\n[dos]\n#            xms: Enable XMS support.\n#            ems: Enable EMS support.\n#            umb: Enable UMB support.\n# keyboardlayout: Language code of the keyboard layout (or none).\n\nxms=true\nems=false\numb=true\nkeyboardlayout=auto\n\n[ipx]\n# ipx: Enable ipx over UDP/IP emulation.\n\nipx=false\n\n[autoexec]\n# Lines in this section will be run at startup.\n# You can put your MOUNT lines here.\n\nMOUNT C: /games\nC:\n"
  },
  {
    "path": "game-engine/conf/dosbox/dosbox.conf.template",
    "content": "set border 0\nexec dosbox -conf ~/.dosbox/dosbox.conf -fullscreen\nroot@9fb8fc07e1da:~# cat .dosbox/dosbox.conf\n# This is the configurationfile for DOSBox 0.74. (Please use the latest version of DOSBox)\n# Lines starting with a # are commentlines and are ignored by DOSBox.\n# They are used to (briefly) document the effect of each option.\n\n[sdl]\n#       fullscreen: Start dosbox directly in fullscreen. (Press ALT-Enter to go back)\n#       fulldouble: Use double buffering in fullscreen. It can reduce screen flickering, but it can also result in a slow DOSBox.\n#   fullresolution: What resolution to use for fullscreen: original or fixed size (e.g. 1024x768).\n#                     Using your monitor's native resolution with aspect=true might give the best results.\n#                     If you end up with small window on a large screen, try an output different from surface.\n# windowresolution: Scale the window to this size IF the output device supports hardware scaling.\n#                     (output=surface does not!)\n#           output: What video system to use for output.\n#                   Possible values: surface, overlay, opengl, openglnb.\n#         autolock: Mouse will automatically lock, if you click on the screen. (Press CTRL-F10 to unlock)\n#      sensitivity: Mouse sensitivity.\n#      waitonerror: Wait before closing the console if dosbox has an error.\n#         priority: Priority levels for dosbox. Second entry behind the comma is for when dosbox is not focused/minimized.\n#                     pause is only valid for the second entry.\n#                   Possible values: lowest, lower, normal, higher, highest, pause.\n#       mapperfile: File used to load/save the key/event mappings from. Resetmapper only works with the defaul value.\n#     usescancodes: Avoid usage of symkeys, might not work on all operating systems.\n\nfullscreen=true\nfulldouble=false\nfullresolution=0x0\nwindowresolution=0x0\noutput=opengl\nautolock=true\nsensitivity=100\nwaitonerror=true\npriority=higher,normal\nmapperfile=mapper-0.74.map\nusescancodes=false\n\n[dosbox]\n# language: Select another language file.\n#  machine: The type of machine tries to emulate.\n#           Possible values: hercules, cga, tandy, pcjr, ega, vgaonly, svga_s3, svga_et3000, svga_et4000, svga_paradise, vesa_nolfb, vesa_oldvbe.\n# captures: Directory where things like wave, midi, screenshot get captured.\n#  memsize: Amount of memory DOSBox has in megabytes.\n#             This value is best left at its default to avoid problems with some games,\n#             though few games might require a higher value.\n#             There is generally no speed advantage when raising this value.\n\nlanguage=\nmachine=svga_s3\ncaptures=capture\nmemsize=16\n\n[render]\n# frameskip: How many frames DOSBox skips before drawing one.\n#    aspect: Do aspect correction, if your output method doesn't support scaling this can slow things down!.\n#    scaler: Scaler used to enlarge/enhance low resolution modes.\n#              If 'forced' is appended, then the scaler will be used even if the result might not be desired.\n#            Possible values: none, normal2x, normal3x, advmame2x, advmame3x, advinterp2x, advinterp3x, hq2x, hq3x, 2xsai, super2xsai, supereagle, tv2x, tv3x, rgb2x, rgb3x, scan2x, scan3x.\n\nframeskip=0\naspect=false\nscaler=none\n\n[cpu]\n#      core: CPU Core used in emulation. auto will switch to dynamic if available and appropriate.\n#            Possible values: auto, dynamic, normal, simple.\n#   cputype: CPU Type used in emulation. auto is the fastest choice.\n#            Possible values: auto, 386, 386_slow, 486_slow, pentium_slow, 386_prefetch.\n#    cycles: Amount of instructions DOSBox tries to emulate each millisecond.\n#            Setting this value too high results in sound dropouts and lags.\n#            Cycles can be set in 3 ways:\n#              'auto'          tries to guess what a game needs.\n#                              It usually works, but can fail for certain games.\n#              'fixed #number' will set a fixed amount of cycles. This is what you usually need if 'auto' fails.\n#                              (Example: fixed 4000).\n#              'max'           will allocate as much cycles as your computer is able to handle.\n#\n#            Possible values: auto, fixed, max.\n#   cycleup: Amount of cycles to decrease/increase with keycombo.(CTRL-F11/CTRL-F12)\n# cycledown: Setting it lower than 100 will be a percentage.\n\ncore=auto\ncputype=auto\ncycles=auto\ncycleup=10\ncycledown=20\n\n[mixer]\n#   nosound: Enable silent mode, sound is still emulated though.\n#      rate: Mixer sample rate, setting any device's rate higher than this will probably lower their sound quality.\n#            Possible values: 44100, 48000, 32000, 22050, 16000, 11025, 8000, 49716.\n# blocksize: Mixer block size, larger blocks might help sound stuttering but sound will also be more lagged.\n#            Possible values: 1024, 2048, 4096, 8192, 512, 256.\n# prebuffer: How many milliseconds of data to keep on top of the blocksize.\n\nnosound=false\nrate=44100\nblocksize=1024\nprebuffer=20\n\n[midi]\n#     mpu401: Type of MPU-401 to emulate.\n#             Possible values: intelligent, uart, none.\n# mididevice: Device that will receive the MIDI data from MPU-401.\n#             Possible values: default, win32, alsa, oss, coreaudio, coremidi, none.\n# midiconfig: Special configuration options for the device driver. This is usually the id of the device you want to use.\n#               See the README/Manual for more details.\n\nmpu401=intelligent\nmididevice=default\nmidiconfig=\n\n[sblaster]\n#  sbtype: Type of Soundblaster to emulate. gb is Gameblaster.\n#          Possible values: sb1, sb2, sbpro1, sbpro2, sb16, gb, none.\n#  sbbase: The IO address of the soundblaster.\n#          Possible values: 220, 240, 260, 280, 2a0, 2c0, 2e0, 300.\n#     irq: The IRQ number of the soundblaster.\n#          Possible values: 7, 5, 3, 9, 10, 11, 12.\n#     dma: The DMA number of the soundblaster.\n#          Possible values: 1, 5, 0, 3, 6, 7.\n#    hdma: The High DMA number of the soundblaster.\n#          Possible values: 1, 5, 0, 3, 6, 7.\n# sbmixer: Allow the soundblaster mixer to modify the DOSBox mixer.\n# oplmode: Type of OPL emulation. On 'auto' the mode is determined by sblaster type. All OPL modes are Adlib-compatible, except for 'cms'.\n#          Possible values: auto, cms, opl2, dualopl2, opl3, none.\n#  oplemu: Provider for the OPL emulation. compat might provide better quality (see oplrate as well).\n#          Possible values: default, compat, fast.\n# oplrate: Sample rate of OPL music emulation. Use 49716 for highest quality (set the mixer rate accordingly).\n#          Possible values: 44100, 49716, 48000, 32000, 22050, 16000, 11025, 8000.\n\nsbtype=sb16\nsbbase=220\nirq=7\ndma=1\nhdma=5\nsbmixer=true\noplmode=auto\noplemu=default\noplrate=44100\n\n[gus]\n#      gus: Enable the Gravis Ultrasound emulation.\n#  gusrate: Sample rate of Ultrasound emulation.\n#           Possible values: 44100, 48000, 32000, 22050, 16000, 11025, 8000, 49716.\n#  gusbase: The IO base address of the Gravis Ultrasound.\n#           Possible values: 240, 220, 260, 280, 2a0, 2c0, 2e0, 300.\n#   gusirq: The IRQ number of the Gravis Ultrasound.\n#           Possible values: 5, 3, 7, 9, 10, 11, 12.\n#   gusdma: The DMA channel of the Gravis Ultrasound.\n#           Possible values: 3, 0, 1, 5, 6, 7.\n# ultradir: Path to Ultrasound directory. In this directory\n#           there should be a MIDI directory that contains\n#           the patch files for GUS playback. Patch sets used\n#           with Timidity should work fine.\n\ngus=false\ngusrate=44100\ngusbase=240\ngusirq=5\ngusdma=3\nultradir=C:\\ULTRASND\n\n[speaker]\n# pcspeaker: Enable PC-Speaker emulation.\n#    pcrate: Sample rate of the PC-Speaker sound generation.\n#            Possible values: 44100, 48000, 32000, 22050, 16000, 11025, 8000, 49716.\n#     tandy: Enable Tandy Sound System emulation. For 'auto', emulation is present only if machine is set to 'tandy'.\n#            Possible values: auto, on, off.\n# tandyrate: Sample rate of the Tandy 3-Voice generation.\n#            Possible values: 44100, 48000, 32000, 22050, 16000, 11025, 8000, 49716.\n#    disney: Enable Disney Sound Source emulation. (Covox Voice Master and Speech Thing compatible).\n\npcspeaker=true\npcrate=44100\ntandy=auto\ntandyrate=44100\ndisney=true\n\n[joystick]\n# joysticktype: Type of joystick to emulate: auto (default), none,\n#               2axis (supports two joysticks),\n#               4axis (supports one joystick, first joystick used),\n#               4axis_2 (supports one joystick, second joystick used),\n#               fcs (Thrustmaster), ch (CH Flightstick).\n#               none disables joystick emulation.\n#               auto chooses emulation depending on real joystick(s).\n#               (Remember to reset dosbox's mapperfile if you saved it earlier)\n#               Possible values: auto, 2axis, 4axis, 4axis_2, fcs, ch, none.\n#        timed: enable timed intervals for axis. Experiment with this option, if your joystick drifts (away).\n#     autofire: continuously fires as long as you keep the button pressed.\n#       swap34: swap the 3rd and the 4th axis. can be useful for certain joysticks.\n#   buttonwrap: enable button wrapping at the number of emulated buttons.\n\njoysticktype=auto\ntimed=true\nautofire=false\nswap34=false\nbuttonwrap=false\n\n[serial]\n# serial1: set type of device connected to com port.\n#          Can be disabled, dummy, modem, nullmodem, directserial.\n#          Additional parameters must be in the same line in the form of\n#          parameter:value. Parameter for all types is irq (optional).\n#          for directserial: realport (required), rxdelay (optional).\n#                           (realport:COM1 realport:ttyS0).\n#          for modem: listenport (optional).\n#          for nullmodem: server, rxdelay, txdelay, telnet, usedtr,\n#                         transparent, port, inhsocket (all optional).\n#          Example: serial1=modem listenport:5000\n#          Possible values: dummy, disabled, modem, nullmodem, directserial.\n# serial2: see serial1\n#          Possible values: dummy, disabled, modem, nullmodem, directserial.\n# serial3: see serial1\n#          Possible values: dummy, disabled, modem, nullmodem, directserial.\n# serial4: see serial1\n#          Possible values: dummy, disabled, modem, nullmodem, directserial.\n\nserial1=dummy\nserial2=dummy\nserial3=disabled\nserial4=disabled\n\n[dos]\n#            xms: Enable XMS support.\n#            ems: Enable EMS support.\n#            umb: Enable UMB support.\n# keyboardlayout: Language code of the keyboard layout (or none).\n\nxms=true\nems=false\numb=true\nkeyboardlayout=auto\n\n[ipx]\n# ipx: Enable ipx over UDP/IP emulation.\n\nipx=false\n\n[autoexec]\n# Lines in this section will be run at startup.\n# You can put your MOUNT lines here.\n\n@ECHO OFF\nMOUNT C: /games\nC:\nCD ${GAME_DIR}\necho \"To run this game just type: ${GAME_EXE} + enter\"\n"
  },
  {
    "path": "game-engine/conf/novnc/background_patch.diff",
    "content": "diff --git a/core/rfb.js b/core/rfb.js\nindex 7c4e0c9..7217e7c 100644\n--- a/core/rfb.js\n+++ b/core/rfb.js\n@@ -152,7 +152,7 @@ export default function RFB(target, url, options) {\n     this._screen.style.width = '100%';\n     this._screen.style.height = '100%';\n     this._screen.style.overflow = 'auto';\n-    this._screen.style.backgroundColor = 'rgb(40, 40, 40)';\n+    this._screen.style.backgroundColor = 'black';\n     this._canvas = document.createElement('canvas');\n     this._canvas.style.margin = 'auto';\n     // Some browsers add an outline on focus\n"
  },
  {
    "path": "game-engine/conf/novnc/vnc_lite.html",
    "content": "<!DOCTYPE html>\n<html>\n\n<head>\n\n    <!--\n    noVNC example: lightweight example using minimal UI and features\n    Copyright (C) 2012 Joel Martin\n    Copyright (C) 2017 Samuel Mannehed for Cendio AB\n    noVNC is licensed under the MPL 2.0 (see LICENSE.txt)\n    This file is licensed under the 2-Clause BSD license (see LICENSE.txt).\n\n    Connect parameters are provided in query string:\n        http://example.com/?host=HOST&port=PORT&encrypt=1\n    or the fragment:\n        http://example.com/#host=HOST&port=PORT&encrypt=1\n    -->\n    <title>noVNC</title>\n\n    <meta charset=\"utf-8\">\n\n    <!-- Always force latest IE rendering engine (even in intranet) & Chrome Frame\n                Remove this if you use the .htaccess -->\n    <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge,chrome=1\">\n\n    <!-- Icons (see Makefile for what the sizes are for) -->\n    <link rel=\"icon\" sizes=\"16x16\" type=\"image/png\" href=\"app/images/icons/novnc-16x16.png\">\n    <link rel=\"icon\" sizes=\"24x24\" type=\"image/png\" href=\"app/images/icons/novnc-24x24.png\">\n    <link rel=\"icon\" sizes=\"32x32\" type=\"image/png\" href=\"app/images/icons/novnc-32x32.png\">\n    <link rel=\"icon\" sizes=\"48x48\" type=\"image/png\" href=\"app/images/icons/novnc-48x48.png\">\n    <link rel=\"icon\" sizes=\"60x60\" type=\"image/png\" href=\"app/images/icons/novnc-60x60.png\">\n    <link rel=\"icon\" sizes=\"64x64\" type=\"image/png\" href=\"app/images/icons/novnc-64x64.png\">\n    <link rel=\"icon\" sizes=\"72x72\" type=\"image/png\" href=\"app/images/icons/novnc-72x72.png\">\n    <link rel=\"icon\" sizes=\"76x76\" type=\"image/png\" href=\"app/images/icons/novnc-76x76.png\">\n    <link rel=\"icon\" sizes=\"96x96\" type=\"image/png\" href=\"app/images/icons/novnc-96x96.png\">\n    <link rel=\"icon\" sizes=\"120x120\" type=\"image/png\" href=\"app/images/icons/novnc-120x120.png\">\n    <link rel=\"icon\" sizes=\"144x144\" type=\"image/png\" href=\"app/images/icons/novnc-144x144.png\">\n    <link rel=\"icon\" sizes=\"152x152\" type=\"image/png\" href=\"app/images/icons/novnc-152x152.png\">\n    <link rel=\"icon\" sizes=\"192x192\" type=\"image/png\" href=\"app/images/icons/novnc-192x192.png\">\n    <!-- Firefox currently mishandles SVG, see #1419039\n    <link rel=\"icon\" sizes=\"any\" type=\"image/svg+xml\" href=\"app/images/icons/novnc-icon.svg\">\n    -->\n    <!-- Repeated last so that legacy handling will pick this -->\n    <link rel=\"icon\" sizes=\"16x16\" type=\"image/png\" href=\"app/images/icons/novnc-16x16.png\">\n\n    <!-- Apple iOS Safari settings -->\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no\">\n    <meta name=\"apple-mobile-web-app-capable\" content=\"yes\" />\n    <meta name=\"apple-mobile-web-app-status-bar-style\" content=\"black-translucent\" />\n    <!-- Home Screen Icons (favourites and bookmarks use the normal icons) -->\n    <link rel=\"apple-touch-icon\" sizes=\"60x60\" type=\"image/png\" href=\"app/images/icons/novnc-60x60.png\">\n    <link rel=\"apple-touch-icon\" sizes=\"76x76\" type=\"image/png\" href=\"app/images/icons/novnc-76x76.png\">\n    <link rel=\"apple-touch-icon\" sizes=\"120x120\" type=\"image/png\" href=\"app/images/icons/novnc-120x120.png\">\n    <link rel=\"apple-touch-icon\" sizes=\"152x152\" type=\"image/png\" href=\"app/images/icons/novnc-152x152.png\">\n\n    <!-- Stylesheets -->\n    <link rel=\"stylesheet\" href=\"app/styles/lite.css\">\n\n    <!--\n    <script type='text/javascript'\n        src='http://getfirebug.com/releases/lite/1.2/firebug-lite-compressed.js'></script>\n    -->\n\n    <!-- promise polyfills promises for IE11 -->\n    <script src=\"vendor/promise.js\"></script>\n    <!-- ES2015/ES6 modules polyfill -->\n    <script type=\"module\">\n        window._noVNC_has_module_support = true;\n    </script>\n    <script>\n        window.addEventListener(\"load\", function () {\n            if (window._noVNC_has_module_support) return;\n            var loader = document.createElement(\"script\");\n            loader.src = \"vendor/browser-es-module-loader/dist/browser-es-module-loader.js\";\n            document.head.appendChild(loader);\n        });\n    </script>\n\n    <!-- actual script modules -->\n    <script type=\"module\" crossorigin=\"anonymous\">\n        // Load supporting scripts\n        import * as WebUtil from './app/webutil.js';\n        import RFB from './core/rfb.js';\n        import WebAudio from './core/webaudio.js'\n\n        var rfb;\n        var desktopName;\n\n        let audioStarted = false;\n\n        function updateDesktopName(e) {\n            desktopName = e.detail.name;\n        }\n        function credentials(e) {\n            var html;\n\n            var form = document.createElement('form');\n            form.innerHTML = '<label></label>';\n            form.innerHTML += '<input type=password size=10 id=\"password_input\">';\n            form.onsubmit = setPassword;\n\n            // bypass status() because it sets text content\n            document.getElementById('noVNC_status_bar').setAttribute(\"class\", \"noVNC_status_warn\");\n            document.getElementById('noVNC_status').innerHTML = '';\n            document.getElementById('noVNC_status').appendChild(form);\n            document.getElementById('noVNC_status').querySelector('label').textContent = 'Password Required: ';\n        }\n        function setPassword() {\n            rfb.sendCredentials({ password: document.getElementById('password_input').value });\n            return false;\n        }\n        function sendCtrlAltDel() {\n            rfb.sendCtrlAltDel();\n            return false;\n        }\n        function machineShutdown() {\n            rfb.machineShutdown();\n            return false;\n        }\n        function machineReboot() {\n            rfb.machineReboot();\n            return false;\n        }\n        function machineReset() {\n            rfb.machineReset();\n            return false;\n        }\n        function status(text, level) {\n            switch (level) {\n                case 'normal':\n                case 'warn':\n                case 'error':\n                    break;\n                default:\n                    level = \"warn\";\n            }\n            document.getElementById('noVNC_status_bar').className = \"noVNC_status_\" + level;\n            document.getElementById('noVNC_status').textContent = text;\n        }\n\n        function connected(e) {\n            var wa = new WebAudio(`ws://${host}:8081/websockify`);\n            document.getElementsByTagName('canvas')[0].addEventListener('keydown', e => {\n                if (audioStarted) {\n                    console.info(\"Audio already started.\");\n                    return;\n                }\n                // Start the sound with alt+(sS)\n                const key = e.key;\n                if (e.altKey && (key.toLowerCase() === \"s\" || e.code == 'KeyS')) {\n                    e.preventDefault();\n                    try {\n                        wa.start();\n                        audioStarted = true;\n                    }\n                    catch (e) {\n                        console.error(e);\n                    }\n\n                }\n            });\n\n            document.getElementById('sendCtrlAltDelButton').disabled = false;\n            if (WebUtil.getConfigVar('encrypt',\n                (window.location.protocol === \"https:\"))) {\n                status(\"Connected (encrypted) to \" + desktopName, \"normal\");\n            } else {\n                status(\"Connected (unencrypted) to \" + desktopName, \"normal\");\n            }\n        }\n\n        function disconnected(e) {\n            document.getElementById('sendCtrlAltDelButton').disabled = true;\n            updatePowerButtons();\n            if (e.detail.clean) {\n                status(\"Disconnected\", \"normal\");\n            } else {\n                status(\"Something went wrong, connection is closed\", \"error\");\n            }\n        }\n\n        function updatePowerButtons() {\n            var powerbuttons;\n            powerbuttons = document.getElementById('noVNC_power_buttons');\n            if (rfb.capabilities.power) {\n                powerbuttons.className = \"noVNC_shown\";\n            } else {\n                powerbuttons.className = \"noVNC_hidden\";\n            }\n        }\n\n        document.getElementById('sendCtrlAltDelButton').onclick = sendCtrlAltDel;\n        document.getElementById('machineShutdownButton').onclick = machineShutdown;\n        document.getElementById('machineRebootButton').onclick = machineReboot;\n        document.getElementById('machineResetButton').onclick = machineReset;\n\n        WebUtil.init_logging(WebUtil.getConfigVar('logging', 'warn'));\n        document.title = WebUtil.getConfigVar('title', 'noVNC');\n        // By default, use the host and port of server that served this file\n        var host = WebUtil.getConfigVar('host', window.location.hostname);\n        var port = WebUtil.getConfigVar('port', window.location.port);\n\n        // if port == 80 (or 443) then it won't be present and should be\n        // set manually\n        if (!port) {\n            if (window.location.protocol.substring(0, 5) == 'https') {\n                port = 443;\n            }\n            else if (window.location.protocol.substring(0, 4) == 'http') {\n                port = 80;\n            }\n        }\n\n        var password = WebUtil.getConfigVar('password', '');\n        var path = WebUtil.getConfigVar('path', 'websockify');\n\n        // If a token variable is passed in, set the parameter in a cookie.\n        // This is used by nova-novncproxy.\n        var token = WebUtil.getConfigVar('token', null);\n        if (token) {\n            // if token is already present in the path we should use it\n            path = WebUtil.injectParamIfMissing(path, \"token\", token);\n\n            WebUtil.createCookie('token', token, 1)\n        }\n\n        (function () {\n\n            status(\"Connecting\", \"normal\");\n\n            if ((!host) || (!port)) {\n                status('Must specify host and port in URL', 'error');\n            }\n\n            var url;\n\n            if (WebUtil.getConfigVar('encrypt',\n                (window.location.protocol === \"https:\"))) {\n                url = 'wss';\n            } else {\n                url = 'ws';\n            }\n\n            url += '://' + host;\n            if (port) {\n                url += ':' + port;\n            }\n            url += '/' + path;\n\n            rfb = new RFB(document.body, url,\n                {\n                    repeaterID: WebUtil.getConfigVar('repeaterID', ''),\n                    shared: WebUtil.getConfigVar('shared', true),\n                    credentials: { password: password }\n                }\n            );\n            rfb.viewOnly = WebUtil.getConfigVar('view_only', false);\n            rfb.addEventListener(\"connect\", connected);\n            rfb.addEventListener(\"disconnect\", disconnected);\n            rfb.addEventListener(\"capabilities\", function () { updatePowerButtons(); });\n            rfb.addEventListener(\"credentialsrequired\", credentials);\n            rfb.addEventListener(\"desktopname\", updateDesktopName);\n            rfb.scaleViewport = WebUtil.getConfigVar('scale', false);\n            rfb.resizeSession = WebUtil.getConfigVar('resize', false);\n        })();\n    </script>\n\n    <style type=\"text/css\">\n        #noVNC_status_bar {\n            display: none;\n        }\n    </style>\n</head>\n\n<body>\n    <div id=\"noVNC_status_bar\">\n        <div id=\"noVNC_left_dummy_elem\"></div>\n        <div id=\"noVNC_status\">Loading</div>\n        <div id=\"noVNC_buttons\">\n            <input type=button value=\"Send CtrlAltDel\" id=\"sendCtrlAltDelButton\" class=\"noVNC_shown\">\n            <span id=\"noVNC_power_buttons\" class=\"noVNC_hidden\">\n                <input type=button value=\"Shutdown\" id=\"machineShutdownButton\">\n                <input type=button value=\"Reboot\" id=\"machineRebootButton\">\n                <input type=button value=\"Reset\" id=\"machineResetButton\">\n            </span>\n        </div>\n    </div>\n</body>\n\n</html>"
  },
  {
    "path": "game-engine/conf/supervisord.conf",
    "content": "[supervisord]\nnodaemon=true\npidfile=/home/retrogames/supervisord.pid\nlogfile=/home/retrogames/supervisord.log\n\n[program:x11vnc]\ncommand=x11vnc -forever -shared\nstdout_logfile=/home/retrogames/x11vnc.log\nredirect_stderr=true\n\n[program:xvfb]\ncommand=Xvfb :0 -screen 0 \"%(ENV_DISPLAY_SETTINGS)s\" -listen tcp -ac\nstdout_logfile=/home/retrogames/xvfb.log\nredirect_stderr=true\n\n[program:websockify_vnc]\ncommand=websockify --web /usr/share/novnc 8080 localhost:5900\nstdout_logfile=/home/retrogames/websockify-vnc.log\nredirect_stderr=true\n\n[program:pulseaudio]\ncommand=/usr/bin/pulseaudio --disallow-module-loading -vvvv --disallow-exit --exit-idle-time=-1\nstdout_logfile=/home/retrogames/pulseaudio.log\nredirect_stderr=true\n\n[program:audiostream]\ncommand=tcpserver 127.0.0.1 5901 gst-launch-1.0 -q pulsesrc server=/tmp/pulseaudio.socket ! audio/x-raw, channels=2, rate=24000 ! cutter ! opusenc ! webmmux ! fdsink fd=1\nstdout_logfile=/home/retrogames/audiostream.log\nredirect_stderr=true\n\n[program:websockify_audio]\ncommand=websockify 8081 localhost:5901\nstdout_logfile=/home/retrogames/websockify-audio.log\nredirect_stderr=true\n\n[program:dosbox]\ncommand=/entrypoint.sh\nstdout_logfile=/home/retrogames/retrogames.log\nautostart=true\nautorestart=unexpected\nstartsecs=10\nstartretries=3\nexitcodes=0,255\nredirect_stderr=true\n"
  },
  {
    "path": "game-engine/conf/webaudio.js",
    "content": "export default class WebAudio {\n    constructor(url) {\n        this.url = url\n\n        this.connected = false;\n\n        //constants for audio behavoir\n        this.maximumAudioLag = 1.5; //amount of seconds we can potentially be behind the server audio stream\n        this.syncLagInterval = 5000; //check every x milliseconds if we are behind the server audio stream\n        this.updateBufferEvery = 20; //add recieved data to the player buffer every x milliseconds\n        this.reduceBufferInterval = 500; //trim the output audio stream buffer every x milliseconds so we don't overflow\n        this.maximumSecondsOfBuffering = 1; //maximum amount of data to store in the play buffer\n        this.connectionCheckInterval = 500; //check the connection every x milliseconds\n\n        //register all our background timers. these need to be created only once - and will run independent of the object's streams/properties\n        setInterval(() => this.updateQueue(), this.updateBufferEvery);\n        setInterval(() => this.syncInterval(), this.syncLagInterval);\n        setInterval(() => this.reduceBuffer(), this.reduceBufferInterval);\n        setInterval(() => this.tryLastPacket(), this.connectionCheckInterval);\n\n    }\n\n    //registers all the event handlers for when this stream is closed - or when data arrives.\n    registerHandlers() {\n        this.mediaSource.addEventListener('sourceended', e => this.socketDisconnected(e))\n        this.mediaSource.addEventListener('sourceclose', e => this.socketDisconnected(e))\n        this.mediaSource.addEventListener('error', e => this.socketDisconnected(e))\n        this.buffer.addEventListener('error', e => this.socketDisconnected(e))\n        this.buffer.addEventListener('abort', e => this.socketDisconnected(e))\n    }\n\n    //starts the web audio stream. only call this method on button click.\n    start() {\n        if (!!this.connected) return;\n        if (!!this.audio) this.audio.remove();\n        this.queue = null;\n\n        this.mediaSource = new MediaSource()\n        this.mediaSource.addEventListener('sourceopen', e => this.onSourceOpen())\n        //first we need a media source - and an audio object that contains it.\n        this.audio = document.createElement('audio');\n        this.audio.src = window.URL.createObjectURL(this.mediaSource);\n\n        //start our stream - we can only do this on user input\n        this.audio.play();\n    }\n\n    wsConnect() {\n        if (!!this.socket) this.socket.close();\n\n        this.socket = new WebSocket(this.url, ['binary', 'base64'])\n        this.socket.binaryType = 'arraybuffer'\n        this.socket.addEventListener('message', e => this.websocketDataArrived(e), false);\n    }\n\n    //this is called when the media source contains data\n    onSourceOpen(e) {\n        this.buffer = this.mediaSource.addSourceBuffer('audio/webm; codecs=\"opus\"')\n        this.registerHandlers();\n        this.wsConnect();\n    }\n\n    //whenever data arrives in our websocket this is called.\n    websocketDataArrived(e) {\n        this.lastPacket = Date.now();\n        this.connected = true;\n        this.queue = this.queue == null ? e.data : this.concat(this.queue, e.data);\n    }\n\n    //whenever a disconnect happens this is called.\n    socketDisconnected(e) {\n        console.log(e);\n        this.connected = false;\n    }\n\n    tryLastPacket() {\n        if (this.lastPacket == null) return;\n        if ((Date.now() - this.lastPacket) > 1000) {\n            this.socketDisconnected('timeout');\n        }\n    }\n\n    //this updates the buffer with the data from our queue\n    updateQueue() {\n        if (!(!!this.queue && !!this.buffer && !this.buffer.updating)) {\n            return;\n        }\n\n        this.buffer.appendBuffer(this.queue);\n        this.queue = null;\n    }\n\n    //reduces the stream buffer to the minimal size that we need for streaming\n    reduceBuffer() {\n        if (!(this.buffer && !this.buffer.updating && !!this.audio && !!this.audio.currentTime && this.audio.currentTime > 1)) {\n            return;\n        }\n\n        this.buffer.remove(0, this.audio.currentTime - 1);\n    }\n\n    //synchronizes the current time of the stream with the server\n    syncInterval() {\n        if (!(this.audio && this.audio.currentTime && this.audio.currentTime > 1 && this.buffer && this.buffer.buffered && this.buffer.buffered.length > 1)) {\n            return;\n        }\n\n        var currentTime = this.audio.currentTime;\n        var targetTime = this.buffer.buffered.end(this.buffer.buffered.length - 1);\n\n        if (targetTime > (currentTime + this.maximumAudioLag)) this.audio.fastSeek(targetTime);\n    }\n\n    //joins two data arrays - helper function\n    concat(buffer1, buffer2) {\n        var tmp = new Uint8Array(buffer1.byteLength + buffer2.byteLength);\n        tmp.set(new Uint8Array(buffer1), 0);\n        tmp.set(new Uint8Array(buffer2), buffer1.byteLength);\n        return tmp.buffer;\n    };\n}\n"
  },
  {
    "path": "game-engine/entrypoint.sh",
    "content": "#!/bin/bash\nset -e\nexport DOSCONF=$(dosbox -printconf)\nexport GAME_ROOT=${GAME_ROOT:-/games}\nexport DOSBOX_CLI=${DOSBOX_CLI:-n}\nsleep 5\n\nif [ -z ${GAME_DIR} ]\nthen\n    echo \"You should pass the game directory you want to run, eg: \\\"GAME_DIR=DOOM\\\" exiting...\"\n    exit 255\nfi\n\nif [ -z ${GAME_EXE} ]\nthen\n    echo \"You should pass the game executable you want to run, eg: \\\"GAME_EXE=DOOM\\\" exiting...\"\n    exit 255\nfi\n\nif [ ${DOSBOX_CLI} == 'n' ]; then\n    if [ ! -f ${GAME_ROOT}/${GAME_DIR}/${GAME_EXE} ]\n    then\n        echo \"I cannot find the executable: ${GAME_ROOT}/${GAME_DIR}/${GAME_EXE}\"\n        exit 255\n    fi\n    envsubst < /dosbox/dosbox.conf.template > ~/.dosbox/dosbox.conf\n    exec dosbox -conf ~/.dosbox/dosbox.conf\nelse\n    envsubst < /dosbox/dosbox.cli.conf.template > ~/.dosbox/dosbox.conf\n    exec dosbox -conf ~/.dosbox/dosbox.conf\nfi\n\n\n"
  },
  {
    "path": "game-engine/run.sh",
    "content": "docker rm -f retrogames-k8s || true\ndocker run \\\n  --detach \\\n  --env DISPLAY_SETTINGS=\"1024x768x24\" \\\n  --env GAME_DIR=${1} \\\n  --env GAME_EXE=\"${2}\" \\\n  --env DOSBOX_CLI=\"n\" \\\n  --publish 8080:8080 \\\n  --publish 8081:8081 \\\n  --rm \\\n  -v $PWD/games:/games \\\n  --name retrogames-k8s \\\n  sparkfabrik/retro-games-k8s:1.0\n  xdg-open http://localhost:8080\n"
  },
  {
    "path": "k8s/manifests/crd-game-controller.yml",
    "content": "apiVersion: apiextensions.k8s.io/v1\nkind: CustomResourceDefinition\nmetadata:\n  # name must match the spec fields below, and be in the form: <plural>.<group>\n  name: games.retro.sparkfabrik.com\nspec:\n  # group name to use for REST API: /apis/<group>/<version>\n  group: retro.sparkfabrik.com\n  # list of versions supported by this CustomResourceDefinition\n  versions:\n    - name: v1\n      # Each version can be enabled/disabled by Served flag.\n      served: true\n      # One and only one version must be marked as the storage version.\n      storage: true\n      schema:\n        openAPIV3Schema:\n          type: object\n          properties:\n            spec:\n              type: object\n              properties:\n                name:\n                  type: string\n                zipUrl:\n                  type: string\n                dir:\n                  type: string\n                exe:\n                  type: string\n              required:\n              - name\n              - zipUrl\n              - dir\n              - exe\n            status:\n             type: object\n             description: GameStatus defines the observed state of Game\n             properties:\n              gameState:\n                type: string\n      subresources:\n        status: {}\n      # The columns we see in the kubectl output.\n      additionalPrinterColumns:\n      - name: Game name\n        type: string\n        description: The game name\n        jsonPath: .spec.name\n      - name: GSURL\n        type: string\n        description: The zip url of this game\n        jsonPath: .spec.zipUrl\n      - name: status\n        type: string\n        description: The game status\n        jsonPath: .status.gameState\n      - name: age\n        type: date\n        description: Age\n        jsonPath: .metadata.creationTimestamp\n  scope: Namespaced\n  names:\n    plural: games\n    singular: game\n    kind: Game\n    shortNames:\n    - gm\n"
  },
  {
    "path": "k8s/manifests/game-controller-cluster-role-binding.yml",
    "content": "apiVersion: rbac.authorization.k8s.io/v1\nkind: ClusterRoleBinding\nmetadata:\n  name: role-game-controller-binding\nroleRef:\n  apiGroup: rbac.authorization.k8s.io\n  kind: ClusterRole\n  name: role-game-controller\nsubjects:\n  - kind: ServiceAccount\n    name: game-controller-service-account\n    namespace: games"
  },
  {
    "path": "k8s/manifests/game-controller-cluster-role.yml",
    "content": "apiVersion: rbac.authorization.k8s.io/v1\nkind: ClusterRole\nmetadata:\n  name: role-game-controller\nrules:\n- apiGroups: [\"retro.sparkfabrik.com\"]\n  resources: [\"games\", \"games/status\"]\n  verbs: [\"*\"]\n- apiGroups: [\"\",]\n  resources: [\"configmaps\", \"events\", \"services\"]\n  verbs: [\"*\"]\n- apiGroups: [\"apps\"]\n  resources: [\"deployments\"]\n  verbs: [\"*\"]"
  },
  {
    "path": "k8s/manifests/game-controller-sa.yml",
    "content": "apiVersion: v1\nkind: ServiceAccount\nmetadata:\n  name: game-controller-service-account\n  namespace: games\n"
  },
  {
    "path": "k8s/manifests/game-controller.yaml",
    "content": "apiVersion: apps/v1\nkind: Deployment\nmetadata:\n  labels:\n    app: game-controller\n  name: game-controller\nspec:\n  replicas: 1\n  selector:\n    matchLabels:\n      app: game-controller\n  strategy:\n    type: Recreate\n  template:\n    metadata:\n      labels:\n        app: game-controller\n    spec:\n      serviceAccount: game-controller-service-account\n      containers:\n      - image: ghcr.io/paolomainardi/additronk8s-game-controller\n        name: additronk8s-game-controller\n"
  },
  {
    "path": "k8s/manifests/namespace.yml",
    "content": "apiVersion: \"v1\"\nkind: Namespace\nmetadata:\n  name: \"games\""
  },
  {
    "path": "k8s/src/game-controller/Dockerfile",
    "content": "FROM node:15-slim\n\nWORKDIR /app\n\nCOPY package* ./\nRUN npm install\n\nCOPY . .\nCMD [\"node\", \"index\"]"
  },
  {
    "path": "k8s/src/game-controller/index.js",
    "content": "import * as k8s from \"@kubernetes/client-node\";\nimport * as crdInformer from \"./lib/crd-informer.js\";\n\n// Connnect to k8s apis.\nconst kc = new k8s.KubeConfig();\nkc.loadFromDefault();\n\nconsole.log(\"\\nWelcome to the Additron Machine\\n\");\n\n// Start the informers.\ncrdInformer.start(kc, k8s);\n"
  },
  {
    "path": "k8s/src/game-controller/lib/api-machinery.js",
    "content": "import * as util from \"./util.js\";\n\nexport const createApiMachinery = (kc, k8s) => {\n  /**\n   * @type {import('@kubernetes/client-node').CustomObjectsApi}\n   */\n  const customApi = kc.makeApiClient(k8s.CustomObjectsApi);\n\n  /**\n   * @type {import('@kubernetes/client-node').CoreV1Api}\n   */\n  const coreApi = kc.makeApiClient(k8s.CoreV1Api);\n\n  /**\n   * @type {import('@kubernetes/client-node').AppsV1Api}\n   */\n  const appsApi = kc.makeApiClient(k8s.AppsV1Api);\n\n  const apiMachinery = {\n    setOwner: function (owner) {\n      if (!owner) {\n        throw `Owner cannot be empty`;\n      }\n      this.owner = owner;\n    },\n\n    /**\n     *\n     */\n    createCrdInformer: function () {\n      return k8s.makeInformer(\n        kc,\n        \"/apis/retro.sparkfabrik.com/v1/games\",\n        () => {\n          return customApi.listClusterCustomObject(\n            \"retro.sparkfabrik.com\",\n            \"v1\",\n            \"games\"\n          );\n        }\n      );\n    },\n\n    updateStatus: async function (status) {\n      const options = {\n        headers: { \"Content-type\": k8s.PatchUtils.PATCH_FORMAT_JSON_PATCH },\n      };\n      return await customApi.patchNamespacedCustomObjectStatus(\n        \"retro.sparkfabrik.com\",\n        \"v1\",\n        this.owner.metadata.namespace,\n        \"games\",\n        this.owner.metadata.name,\n        [\n          {\n            op: \"replace\",\n            path: \"/status\",\n            value: {\n              gameState: status,\n            },\n          },\n        ],\n        undefined,\n        undefined,\n        undefined,\n        options\n      );\n    },\n\n    /**\n     *\n     * @param {*} configmap\n     */\n    saveConfigMap: async function (configmap) {\n      return await coreApi.createNamespacedConfigMap(\n        this.owner.metadata.namespace,\n        configmap\n      );\n    },\n\n    /**\n     *\n     * @param {*} service\n     */\n    saveService: async function (service) {\n      const res = await coreApi.createNamespacedService(\n        this.owner.metadata.namespace,\n        service\n      );\n    },\n\n    /**\n     *\n     * @param {*} deployment\n     */\n    saveDeployment: async function (deployment) {\n      return await appsApi.createNamespacedDeployment(\n        this.owner.metadata.namespace,\n        deployment\n      );\n    },\n\n    saveServices: async () => {},\n    saveIngress: async () => {},\n\n    event: async function (options) {\n      const event = {\n        metadata: {\n          generateName: \"game-event-\",\n        },\n        involvedObject: {\n          kind: this.owner.kind,\n          name: this.owner.metadata.name,\n          uid: this.owner.metadata.uid,\n          namespace: this.owner.metadata.namespace,\n        },\n        reason: options.reason,\n        type: options.type || \"Normal\",\n        lastTimestamp: new Date(),\n        message: options.message,\n      };\n      await coreApi.createNamespacedEvent(this.owner.metadata.namespace, event);\n    },\n\n    /**\n     *\n     * @param {*} type\n     * @param {*} object\n     */\n    save: async function (type, object) {\n      const funcName = `save${type}`;\n      if (!this.owner) {\n        throw `Owner cannot be empty`;\n      }\n      if (!object) {\n        throw `Object cannot be empty`;\n      }\n      if (typeof this[funcName] !== \"function\") {\n        throw `${funcName} is not a valid function, aborting.`;\n      }\n      const addLabels = util.addDefaultLabels(object, this.owner);\n      const final = util.addOwnerReference(addLabels, this.owner);\n      return await this[funcName](final);\n    },\n  };\n\n  return apiMachinery;\n};\n"
  },
  {
    "path": "k8s/src/game-controller/lib/crd-informer.js",
    "content": "import { createApiMachinery } from \"./api-machinery.js\";\nimport { saveGame, deployGame } from \"./game-engine.js\";\n\n/**\n * @param {import('@kubernetes/client-node').KubeConfig} kc - Kubeconfig\n * @param {import('@kubernetes/client-node')} k8s - K8s\n */\nexport const start = (kc, k8s) => {\n  const machine = createApiMachinery(kc, k8s);\n  const crdInformer = machine.createCrdInformer();\n\n  crdInformer.on(\"add\", async (gameObject) => {\n    try {\n      if (process.env.DEBUG) {\n        console.log(JSON.stringify(gameObject, null, 2));\n      }\n      // TODO: Check if this game already exists.\n      machine.setOwner(gameObject);\n\n      // Get default variables.\n      const name = gameObject.spec.name;\n\n      // Download and save game.\n      console.log(`Reading cloud floppy disks of \"${name}\" in progress... 💾`);\n      const configmaps = await saveGame(gameObject, machine);\n\n      // Deploy game.\n      console.log(`Great! Game downloaded, now saving it locally.... ⌛`);\n      await deployGame(gameObject, configmaps, machine);\n\n      console.log(`Game ready... 🕹️`);\n\n      // Mark as ready.\n      await machine.updateStatus(\"Ready\");\n    } catch (e) {\n      try {\n        await machine.updateStatus(\"Error\");\n      } catch (e) {\n        console.error(\"Cannot update the status.\");\n      } finally {\n        e.response?.body?.message\n          ? console.error(e.response.body.message)\n          : console.error(e);\n      }\n    }\n  });\n\n  // TODO: Handle CRD updates.\n  crdInformer.on(\"update\", async (obj) => {\n    if (process.env.DEBUG) {\n      console.log(JSON.stringify(gameObject, null, 2));\n    }\n  });\n\n  // TODO: Handle CRD deletes.\n  crdInformer.on(\"delete\", async (obj) => {\n    if (process.env.DEBUG) {\n      console.log(JSON.stringify(gameObject, null, 2));\n    }\n  });\n\n  crdInformer.start();\n};\n"
  },
  {
    "path": "k8s/src/game-controller/lib/game-engine.js",
    "content": "import * as path from \"path\";\nimport * as fs from \"fs\";\nimport * as util from \"./util.js\";\n\n/**\n *\n * @param {*} files\n * @param {*} gameObject\n */\nconst createConfigMapsSpec = async (files, gameObject) => {\n  let configmaps = [];\n  let index = 0;\n  for (const file of files) {\n    let filename = path.basename(file).toLowerCase();\n    let data = await fs.promises.readFile(file, { encoding: \"base64\" });\n    let configmap = {\n      metadata: {\n        name: `${gameObject.metadata.name}-${index}`,\n      },\n      binaryData: {\n        [filename]: data,\n      },\n    };\n    configmaps.push(configmap);\n    index++;\n  }\n  return configmaps;\n};\n\n/**\n *\n * @param {*} gameObject\n */\nexport async function downloadAndCreateConfigmapsSpec(gameObject) {\n  try {\n    const path = await util.download(gameObject);\n    const files = await util.splitFile(path);\n    const configmaps = await createConfigMapsSpec(files, gameObject);\n    return configmaps;\n  } catch (e) {\n    throw e;\n  }\n}\n\n/**\n *\n * @param {*} gameObject\n */\nconst createServiceSpec = (gameObject) => {\n  const name = gameObject.metadata.name;\n  const service = {\n    metadata: {\n      name: name,\n      labels: {\n        app: name,\n      },\n    },\n    spec: {\n      selector: {\n        app: name,\n      },\n      ports: [\n        {\n          name: \"vnc\",\n          protocol: \"TCP\",\n          port: 8080,\n          containerPort: 8080,\n        },\n        {\n          name: \"audio\",\n          protocol: \"TCP\",\n          port: 8081,\n          containerPort: 8081,\n        },\n      ],\n    },\n  };\n  return service;\n};\n\n/**\n *\n * @param {*} name\n * @param {*} configmaps\n */\nconst createDeploymentSpec = (gameObject, configmaps) => {\n  const name = gameObject.metadata.name;\n  const deployment = {\n    metadata: {\n      name: name,\n      labels: {\n        app: name,\n      },\n    },\n    spec: {\n      replicas: 1,\n      selector: {\n        matchLabels: {\n          app: name,\n        },\n      },\n      template: {\n        metadata: {\n          labels: {\n            app: name,\n          },\n        },\n        spec: {\n          initContainers: [\n            {\n              name: \"hydrate-game\",\n              image: \"ghcr.io/paolomainardi/additronk8s-game-engine:latest\",\n              imagePullPolicy: \"Always\",\n              command: [\n                \"bash\",\n                \"-c\",\n                \"cd /split && ls | sort -n | xargs cat > /games/game.zip && cd /games && unzip game.zip && rm game.zip\",\n              ],\n            },\n          ],\n          containers: [\n            {\n              name: \"game-engine\",\n              image: \"ghcr.io/paolomainardi/additronk8s-game-engine:latest\",\n              imagePullPolicy: \"Always\",\n              env: [\n                {\n                  name: \"GAME_DIR\",\n                  value: gameObject.spec.dir,\n                },\n                {\n                  name: \"GAME_EXE\",\n                  value: gameObject.spec.exe,\n                },\n                {\n                  name: \"DISPLAY_SETTINGS\",\n                  value: \"1024x768x24\",\n                },\n              ],\n              ports: [\n                {\n                  containerPort: 8080,\n                  containerPort: 8081,\n                },\n              ],\n            },\n          ],\n        },\n      },\n    },\n  };\n  const deploymentWithVolumes = addDeploymentVolumes(deployment, configmaps);\n  return deploymentWithVolumes;\n};\n\n/**\n *\n * @param {*} deployment\n * @param {*} configmaps\n */\nconst addDeploymentVolumes = (deployment, configmaps) => {\n  const deploymentClone = { ...deployment };\n  const volumes = [];\n  const volumeMounts = [];\n  configmaps.forEach((configmap, key) => {\n    volumes.push({\n      name: `configmap-volume-${key}`,\n      configMap: {\n        name: configmap.configmapName,\n        items: [\n          {\n            key: configmap.filename,\n            path: configmap.filename,\n          },\n        ],\n      },\n    });\n    volumeMounts.push({\n      name: `configmap-volume-${key}`,\n      mountPath: `/split/${key}`,\n      subPath: configmap.filename,\n    });\n  });\n\n  // Add the final game volume.\n  const gamesVolume = {\n    name: `games-volume`,\n    emptyDir: {},\n  };\n  const gamesVolumeMount = {\n    name: \"games-volume\",\n    mountPath: \"/games\",\n  };\n  volumes.push(gamesVolume);\n  volumeMounts.push(gamesVolumeMount);\n\n  // Add all volumes to the init container.\n  deploymentClone[\"spec\"][\"template\"][\"spec\"][\"volumes\"] = volumes;\n  deploymentClone[\"spec\"][\"template\"][\"spec\"][\"initContainers\"][0][\n    \"volumeMounts\"\n  ] = volumeMounts;\n\n  // Add only the game volume to the game engine.\n  deploymentClone[\"spec\"][\"template\"][\"spec\"][\"containers\"][0][\n    \"volumeMounts\"\n  ] = [gamesVolumeMount];\n\n  return deploymentClone;\n};\n\n/**\n *\n * @param {*} gameUrl\n * @param {*} machine\n */\nexport const saveGame = async (gameObject, machine) => {\n  try {\n    await machine.event({\n      reason: \"Downloading\",\n      message: `Starting to download game \"${gameObject.spec.name}\" from: ${gameObject.spec.zipUrl}`,\n    });\n\n    const configmaps = await downloadAndCreateConfigmapsSpec(gameObject);\n    for (const configmap of configmaps) {\n      await machine.save(\"ConfigMap\", configmap);\n    }\n\n    await machine.event({\n      reason: \"Downloaded\",\n      message: `Downloaded and splitted in ${configmaps.length} configmaps`,\n    });\n    return configmaps;\n  } catch (e) {\n    await machine.event({\n      reason: \"Failed\",\n      type: \"Warning\",\n      message: `Download of game failed cause: ${JSON.stringify(e.message)}`,\n    });\n    throw e;\n  }\n};\n\n/**\n *\n * @param {*} machine\n */\nexport const deployGame = async (gameObject, configmaps, machine) => {\n  try {\n    const configMapsNames = [];\n    configmaps.map((configmap) => {\n      const filename = Object.keys(configmap.binaryData).pop();\n      configMapsNames.push({\n        filename: filename,\n        configmapName: configmap.metadata.name,\n      });\n    });\n\n    // Create deployment.\n    const deployment = createDeploymentSpec(gameObject, configMapsNames);\n    await machine.save(\"Deployment\", deployment);\n\n    // Create service.\n    const service = createServiceSpec(gameObject);\n    await machine.save(\"Service\", service);\n\n    await machine.event({\n      reason: \"Deployed\",\n      message: `Deployment and service correctly created`,\n    });\n  } catch (e) {\n    await machine.event({\n      reason: \"Failed\",\n      type: \"Warning\",\n      message: `Failed to start the game cause: ${JSON.stringify(e.message)}`,\n    });\n    throw e;\n  }\n};\n"
  },
  {
    "path": "k8s/src/game-controller/lib/util.js",
    "content": "import { Storage } from \"@google-cloud/storage\";\nimport axios from \"axios\";\nimport { URL } from \"url\";\nimport { promisify } from \"util\";\nimport { exec } from \"child_process\";\nimport * as path from \"path\";\nimport { sep } from \"path\";\nimport * as fs from \"fs\";\nimport * as os from \"os\";\n\nexport function addOwnerReference(api, owner) {\n  const newApi = { ...api };\n  newApi[\"metadata\"][\"ownerReferences\"] = [\n    {\n      apiVersion: \"retro.sparkfabrik.com/v1\",\n      controller: true,\n      blockOwnerDeletion: true,\n      kind: \"Game\",\n      name: owner.metadata.name,\n      uid: owner.metadata.uid,\n    },\n  ];\n  return newApi;\n}\n\nexport function addDefaultLabels(api, owner) {\n  if (!api.metadata && owner.metadata) {\n    throw `Objects must contain a metadata property`;\n  }\n  const newApi = { ...api };\n  const defaultLabels = {\n    \"sparkfabrik.com/game\": owner.metadata.name,\n  };\n  newApi.metadata.labels = { ...newApi.metadata.labels, ...defaultLabels };\n  return newApi;\n}\n\nconst mkTempDir = async () => {\n  return await promisify(fs.mkdtemp)(`${os.tmpdir()}${sep}`);\n};\n\n/**\n *\n * @param {*} gameObject\n */\nexport const download = async (gameObject) => {\n  const url = new URL(gameObject.spec.zipUrl);\n  const protocol = url.protocol;\n  if (protocol == \"gs:\") {\n    return await downloadFromGcs(url);\n  }\n  if (protocol === \"http:\" || protocol === \"https:\") {\n    return await downloadFromHttp(url);\n  }\n  throw new Error(`Not supported protocol: ${protocol}`);\n};\n\n/**\n *\n * @param {*} gameObject\n */\nconst downloadFromHttp = async (url) => {\n  const filename = url.pathname.substr(1, url.pathname.length).split('/').pop();\n  const dest = (await mkTempDir()) + `/${filename}`;\n  const response = await axios({\n    method: \"get\",\n    url: url.href,\n    responseType: \"stream\",\n  });\n  response.data.pipe(fs.createWriteStream(dest, response.data));\n  return new Promise((resolve, reject) => {\n    response.data.on(\"end\", () => {\n      resolve(dest);\n    });\n\n    response.data.on(\"error\", (err) => {\n      reject(err);\n    });\n  });\n};\n\nconst downloadFromGcs = async (url) => {\n  const storage = new Storage();\n  const filename = url.pathname.substr(1, url.pathname.length);\n  const dest = (await mkTempDir()) + `/${filename}`;\n  await storage.bucket(url.host).file(filename).download({ destination: dest });\n  return dest;\n};\n\n/**\n *\n * @param {*} game\n */\nexport const splitFile = async (game) => {\n  if (!fs.statSync(game)) {\n    throw `${path} does not exists, cannot split the requested file.`;\n  }\n  const dir = path.dirname(game);\n  const file = path.basename(game);\n  await promisify(exec)(`cd ${dir}; split -d -b 1M ${file} ${file}-split`);\n  const { stdout } = await promisify(exec)(\n    `find ${dir} -name \"${file}-split*\" | sort`\n  );\n  const split = stdout.split(/[\\r\\n|\\n|\\r]/).filter(String);\n  return split;\n};\n"
  },
  {
    "path": "k8s/src/game-controller/package.json",
    "content": "{\n  \"name\": \"game-informer\",\n  \"version\": \"1.0.0\",\n  \"description\": \"\",\n  \"main\": \"index.js\",\n  \"scripts\": {\n    \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\"\n  },\n  \"type\": \"module\",\n  \"author\": \"\",\n  \"license\": \"ISC\",\n  \"dependencies\": {\n    \"@google-cloud/storage\": \"^5.6.0\",\n    \"@kubernetes/client-node\": \"^0.13.0\",\n    \"axios\": \"^0.21.1\"\n  }\n}\n"
  },
  {
    "path": "skaffold.yml",
    "content": "apiVersion: skaffold/v1\nkind: Config\nmetadata:\n  name: additronk8s\nbuild:\n  artifacts:\n  - image: ghcr.io/paolomainardi/additronk8s-game-controller\n    context: k8s/src/game-controller\n    docker:\n      dockerfile: Dockerfile\ndeploy:\n  kubectl:\n    manifests:\n    - ./k8s/manifests/namespace.yml\n    - ./k8s/manifests/*"
  }
]