name: Release Boltzmann CLI
on:
  release:
    types: [published, edited]
jobs:
  docs:
    name: publish docs
    runs-on: ubuntu-latest
    steps:
      - name: download hq
        run: |
          curl -sL https://github.com/chrisdickinson/hq/releases/download/v1.0.0/hq_x64_linux.tar.gz | tar xfz -
          sudo mv hq /usr/local/bin/hq
      - name: download semver-sort
        run: |
          curl -sL https://github.com/chrisdickinson/semver-sort/releases/download/v1.1.0/semver-sort_x64_linux.tar.gz | tar xfz -
          sudo mv semver-sort /usr/local/bin/semver-sort
      - name: download docs
        run: |
          tag=${{ github.ref }}
          current_tag=${tag/refs\/tags\//}
          download_url=$(
            curl -sL https://api.github.com/repos/entropic-dev/boltzmann/releases/tags/${current_tag} | \
              jq -r '.assets[] | .browser_download_url' | \
              grep 'docs'
          )

          all_tags=$(curl -sL https://api.github.com/repos/entropic-dev/boltzmann/releases | jq -r '.[] | .tag_name')

          function get_active_docs() {
            local active=$1
            echo '<a href="#versions">'"$active"'</a>'
            echo "<div>"
            echo "<ul>"
            for tag in $all_tags; do
              echo '<li class="'$(if [[ $tag == $active ]]; then echo "active"; fi; echo " "; if [[ $tag =~ .+-.+ ]]; then echo "prerelease"; fi;)'">'
              echo '<a href="https://www.boltzmann.dev/en/docs/'$tag'">' $tag '</a>'
              echo "</li>"
            done
            echo "</ul>"
            echo '<p><small><label for="prerelease"><input id="prerelease" type="checkbox" /> Show prerelease versions</label></small></p>'
            echo "</div>"
          }

          mkdir docs
          curl -sL $download_url | tar zx -C docs
          cd docs
          for file in $(find . -type f -name '*.html'); do
            contents=$(cat $file | hq '#versions' @<(get_active_docs ${current_tag}))
            echo "$contents" > $file
          done
          aws s3 cp --recursive . s3://www.boltzmann.dev/en/docs/${current_tag} --acl public-read
          latest_tag=$(echo "$all_tags" | semver-sort -r | head -n1)

          if [[ "$current_tag" == "$latest_tag" ]]; then
            aws s3 sync . s3://www.boltzmann.dev/en/docs/latest --acl public-read
          fi

          # rewrite all the old docs with the new version tags.
          for tag in $all_tags; do
            if [[ "$tag" == "$current_tag" ]]; then
              continue
            fi

            aws s3 sync s3://www.boltzmann.dev/en/docs/${tag} .

            for file in $(find . -type f -name '*.html'); do
              contents=$(cat $file | hq '#versions' @<(get_active_docs ${tag}))
              echo "$contents" > $file
            done

            aws s3 sync . s3://www.boltzmann.dev/en/docs/${tag} --acl public-read
          done
        env:
          AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
          AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
          AWS_DEFAULT_REGION: us-west-2

  release:
    name: publish npm package
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - uses: actions/setup-node@v2.1.2
        with:
          node-version: '12'
      - name: download release contents
        run: |
          tag=${{ github.ref }}
          download_urls=$(
            curl -sL https://api.github.com/repos/entropic-dev/boltzmann/releases/tags/${tag/refs\/tags\//} | \
              jq -r '.assets[] | .browser_download_url' | \
              grep -v 'docs'
          )

          mkdir -p boltzmann-cli
          for url in $download_urls; do
            curl -sL $url | tar zx
            name=$(basename $url)
            mv boltzmann boltzmann-cli/${name/.tar.gz/}
          done

          # you're killing me, buster
          mv boltzmann-cli/boltzmann_x64_win32{,.exe}

      - name: create npm package
        run: |
          cd boltzmann-cli
          npm init -y
          cd ..
          tag=${{ github.ref }}
          jq -rM '.description = "The boltzmann CLI" |
                 .bin = "./index.js" |
                 .scripts.test = "echo ok" |
                 .author = "Static T. Raccoon <static-t-raccoon@example.com> (https://entropic-dev.github.io/boltzmann)" |
                 .keywords = ["boltzmann", "scaffold http"] |
                 .license = "Apache-2.0" |
                 .version = "'"${tag/refs\/tags\//}"'"' < boltzmann-cli/package.json > package.json

          mv package.json boltzmann-cli/package.json
          cat boltzmann-cli/package.json

          cat > boltzmann-cli/index.js <<-EOF
          #!/usr/bin/env node
          'use strict'
          const os = require('os')
          const path = require('path')
          const fs = require('fs')
          const spawnSync = require('child_process').spawnSync

          const executable = path.join(__dirname, 'boltzmann_' + os.arch() + '_' + os.platform()) + (os.platform() === 'win32' ? '.exe' : '')

          if (!fs.existsSync(executable)) {
            console.error("Sorry, boltzmann is not yet supported on %s", os.platform())
            console.error()
            console.error("Open an issue here: https://github.com/entropic-dev/boltzmann/issues/new?title=%s+support", os.platform())
            process.exit(1)
          }

          spawnSync(executable, process.argv.slice(2), { stdio: 'inherit' })
          EOF

          cat > ~/.npmrc <<-EOF
          registry=https://registry.npmjs.org/
          //registry.npmjs.org/:_authToken=${{ secrets.NPM_TOKEN }}
          EOF

          cp README.md boltzmann-cli/

          cd boltzmann-cli
          npm publish
          pkg=$(cat package.json)
          echo "$pkg" | jq -rM '.name = "create-boltzmann"' > package.json
          npm publish
