name: lua

on:
  push:
    tags:
      - 'v[0-9]+.[0-9]+.[0-9]+'

permissions:
  contents: read

jobs:
  build:
    runs-on: ${{ matrix.platform.runner }}
    strategy:
      fail-fast: false
      matrix:
        platform:
          - runner: ubuntu-latest
            arch: x86_64
            target: linux-gnu
            pre: lib
            ext: so
          - runner: windows-latest
            arch: x86_64
            target: windows-msvc
            pre:
            ext: dll
          - runner: macos-latest
            arch: aarch64
            target: darwin
            pre: lib
            ext: dylib
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0 # necessary to get last tag
      - uses: dtolnay/rust-toolchain@stable
      - uses: arduino/setup-protoc@v3
        with:
          repo-token: ${{ secrets.GITHUB_TOKEN }}
      - run: cargo build --release --features=lua
      - id: previoustag
        uses: "WyriHaximus/github-action-get-previous-tag@v1"
        with:
          fallback: v0.0.0
      - run: mv target/release/${{matrix.platform.pre}}codemp.${{matrix.platform.ext}} dist/lua/codemp-lua-${{steps.previoustag.outputs.tag}}-${{matrix.platform.arch}}-${{matrix.platform.target}}.${{matrix.platform.ext}}
      - uses: actions/upload-artifact@v4
        with:
          name: codemp-lua-${{ matrix.platform.target }}
          path: dist/lua/codemp-lua-*

  publish:
    runs-on: ubuntu-latest
    needs: [build]
    steps:
      - uses: actions/checkout@v4
      - uses: dtolnay/rust-toolchain@stable
      - uses: arduino/setup-protoc@v3
        with:
          repo-token: ${{ secrets.GITHUB_TOKEN }}
      - uses: leafo/gh-actions-lua@v9
      - uses: leafo/gh-actions-luarocks@v4
      - run: luarocks install --local dkjson # needed to run upload?? ooook luarocks...
      - run: luarocks upload codemp-*.rockspec --api-key ${{ secrets.LUAROCKS_TOKEN }}
        working-directory: dist/lua

  upload:
    runs-on: ubuntu-latest
    needs: [build]
    steps:
      - uses: actions/checkout@v4
      - run: mkdir dist/lua/publish
      - uses: webfactory/ssh-agent@v0.9.0
        with:
          ssh-private-key: ${{ secrets.SSH_PRIVATE_KEY }}
      - uses: actions/download-artifact@v4
        with:
          pattern: codemp-lua-*
          path: dist/lua/publish
      - run: tree dist/lua
      - run: scp -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null dist/lua/annotations.lua dev@codemp.dev:/srv/http/codemp/files/releases/lua/
      # TODO ugly fix to deal with folders on this side...
      - name: copy files on remote
        run: |
          for DIR in $(ls dist/lua/publish); do
            scp -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null dist/lua/publish/$DIR/* dev@codemp.dev:/srv/http/codemp/files/releases/lua/
          done