name: Release

on:
  push:
    tags:
      - 'v*.*.*'

jobs:
  create-release:
    name: Build and Create Tagged Release
    runs-on: ubuntu-latest
    steps:
      - name: Install archive tools
        run: sudo apt install zip

      - name: Checkout source code
        uses: actions/checkout@v2
        with:
          fetch-depth: 0
          ref: ${{ github.event.repository.default_branch }}

      - uses: pnpm/action-setup@v2.0.1
        with:
          version: 8.6.1

      - name: Setup node
        uses: actions/setup-node@v2
        with:
          node-version: 16.x
          cache: 'pnpm'
          cache-dependency-path: 'web/pnpm-lock.yaml'

      - name: Set env
        run: echo "RELEASE_VERSION=${GITHUB_REF#refs/*/}" >> $GITHUB_ENV

      - name: Install dependencies
        run: pnpm install
        working-directory: web

      - name: Install package dependencies
        run: pnpm install
        working-directory: package

      - name: Bump package version
        run: pnpm version ${{ github.ref_name }}
        working-directory: package

      - name: Run build
        run: pnpm build
        working-directory: web
        env:
          CI: false

      - name: Bump manifest version
        run: node .github/actions/bump-manifest-version.js
        env:
          TGT_RELEASE_VERSION: ${{ github.ref_name }}

      - name: Push manifest change
        uses: EndBug/add-and-commit@v8
        with:
          add: fxmanifest.lua
          push: true
          author_name: Manifest Bumper
          author_email: 41898282+github-actions[bot]@users.noreply.github.com
          message: 'chore: bump manifest version to ${{ github.ref_name }}'

      - name: Update tag ref
        uses: EndBug/latest-tag@latest
        with:
          tag-name: ${{ github.ref_name }}

      - name: Bundle files
        run: |
          mkdir -p ./temp/ox_lib
          mkdir -p ./temp/ox_lib/web/
          cp ./{LICENSE,README.md,fxmanifest.lua,init.lua} ./temp/ox_lib
          cp -r ./{imports,resource,locales} ./temp/ox_lib
          cp -r ./web/build ./temp/ox_lib/web/
          cd ./temp && zip -r ../ox_lib.zip ./ox_lib

      - name: Create Release
        uses: 'marvinpinto/action-automatic-releases@v1.2.1'
        id: auto_release
        with:
          repo_token: '${{ secrets.GITHUB_TOKEN }}'
          title: ${{ env.RELEASE_VERSION }}
          prerelease: false
          files: ox_lib.zip

        env:
          CI: false
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

      - name: Publish npm package
        uses: JS-DevTools/npm-publish@v1
        with:
          token: ${{ secrets.NPM_TOKEN }}
          package: './package/package.json'
          access: 'public'
