name: ci
on: [ push, pull_request ]

jobs:
  ci:
    runs-on: ubuntu-latest

    permissions:
      contents: write
      pull-requests: write
      statuses: write

    steps:
      - name: Check out repository code
        uses: actions/checkout@v4
      - name: Setup Node
        uses: actions/setup-node@v4
        with:
          node-version: 20

      - id: version
        name: version
        run: |
          major=${{startsWith(github.event.head_commit.message, '[major]')}}
          minor=${{startsWith(github.event.head_commit.message, '[minor]')}}
          
          echo "major: " $major
          echo "minor: " $minor
          
          if ${{ github.ref_name == 'main' }}; then
            if [[ $major == "true" ]]; then
              newVersion="major"
            elif [[ $minor == "true"  ]]; then
              newVersion="minor"
            else
              newVersion="patch"
            fi
          else
            if [[ $major == "true"  ]]; then
              newVersion="premajor"
            elif [[ $minor == "true"  ]]; then
              newVersion="preminor"
            else
              newVersion="prepatch"
            fi
          fi
          
          echo "using: " $newVersion
          
          npm version "$newVersion" --git-tag-version=false
  
          echo "VERSION=$(npm --silent run version)" >> ${GITHUB_OUTPUT}

      - name: npm ci
        run: npm ci
      - name: build
        run: npm run build

      - name: zip release
        if: github.ref_name == 'main'
        working-directory: dist
        run: zip -r foundryvtt-dice-tower-${{ steps.version.outputs.VERSION }}.zip .

      - name: create tag
        if: github.ref_name == 'main'
        run: |
          git config user.email "ci@git.arindy.de"
          git config user.name "gitea"
          git add package.json
          git add package-lock.json
          git commit -m "[no ci] ${{ steps.version.outputs.VERSION }}"
          git tag ${{ steps.version.outputs.VERSION }} -m "release ${{ steps.version.outputs.VERSION }}"
          git push origin main
          git push origin ${{ steps.version.outputs.VERSION }}

      - name: release
        if: github.ref_name == 'main'
        uses: akkuman/gitea-release-action@v1
        env:
          NODE_OPTIONS: '--experimental-fetch' # if nodejs < 18
        with:
          files: |-
            dist/foundryvtt-dice-tower-${{ steps.version.outputs.VERSION }}.zip
            dist/module.json
          tag_name: ${{ steps.version.outputs.VERSION }}
          name: Release ${{ steps.version.outputs.VERSION }}
