name: Publish Ansible Example

on:
  push:
    tags:
      - 'v*'
  workflow_dispatch: {}

jobs:
  verify:
    name: Verify package
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Setup Node.js 18
        uses: actions/setup-node@v4
        with:
          node-version: '18'

      - name: Install dependencies (packages/@ansible/example)
        working-directory: packages/@ansible/example
        run: |
          # prefer CI install when a lockfile exists, otherwise fall back to install
          if [ -f package-lock.json ] || [ -f pnpm-lock.yaml ] || [ -f yarn.lock ]; then
            npm ci
          else
            npm install
          fi

      - name: Run tests
        working-directory: packages/@ansible/example
        run: npm test

      - name: Run pack-inspect
        working-directory: packages/@ansible/example
        run: npm run pack-inspect

  publish:
    name: Publish to npm
    runs-on: ubuntu-latest
    needs: verify
    if: ${{ ((github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v')) || (github.event_name == 'workflow_dispatch')) && (secrets.NPM_TOKEN != '') }}
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Setup Node.js 18
        uses: actions/setup-node@v4
        with:
          node-version: '18'

      - name: Create ephemeral .npmrc with token
        run: |
          set -euo pipefail
          # write token to a temporary npmrc with restricted permissions (0600)
          printf "//registry.npmjs.org/:_authToken=${{ secrets.NPM_TOKEN }}\n" > ~/.npmrc
          chmod 600 ~/.npmrc

      - name: Publish package
        working-directory: packages/@ansible/example
        env:
          NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
        run: |
          set -euo pipefail
          # publish publicly; rely on npmrc for auth
          npm publish --access public

      - name: Remove ephemeral .npmrc (always)
        if: always()
        run: |
          set -euo pipefail
          # attempt secure removal, fall back to plain removal
          if [ -f ~/.npmrc ]; then
            shred -u -z ~/.npmrc 2>/dev/null || rm -f ~/.npmrc || true
          fi
