name: Release to Production
on:
  push:
    branches:
      - main

jobs:
  build_and_release:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout
        uses: actions/checkout@v3

      - name: Setup Node
        uses: actions/setup-node@v2
        with:
          node-version: 20

      - name: Install Dependencies
        run: npm ci

      - name: Create .env File
        run: echo "VITE_MOST_POPULAR_RELAYS=${{ vars.VITE_MOST_POPULAR_RELAYS }}" > .env

      - name: Create Build
        run: npm run build

      - name: Deploy Build
        run: |
          npm -g install cloudron-surfer
          surfer config --token ${{ secrets.CLOUDRON_SURFER_TOKEN }} --server sigit.io
          surfer put dist/* / --all -d
          surfer put dist/.well-known / --all

      - name: Create Empty Release (assets are posted later)
        run: |
          npm i
          npm i -g semantic-release
          echo "do a semantic-release DRY RUN to make the job fail if there are no changes to release"
          GITEA_TOKEN=${{ secrets.RELEASE_TOKEN }} GITEA_URL=https://git.nostrdev.com/sigit/sigit.io semantic-release --dry-run | grep -q "There are no relevant changes, so no new version is released." && exit 1
          echo "now do the actual release"
          GITEA_TOKEN=${{ secrets.RELEASE_TOKEN }} GITEA_URL=https://git.nostrdev.com/sigit/sigit.io semantic-release

      - name: Upload assets to release
        run: |
          echo "fetching release id"
          RELEASE_ID=`curl -k 'https://git.nostrdev.com/api/v1/repos/sigit/sigit.io/releases/latest?access_token=${{ secrets.RELEASE_TOKEN }}' | jq -r '.id'`
          echo "fetching release body"
          RELEASE_BODY=`curl -k 'https://git.nostrdev.com/api/v1/repos/sigit/sigit.io/releases/latest?access_token=${{ secrets.RELEASE_TOKEN }}' | jq -r '.body'`
          echo "Updating release body"
          curl --data '{"draft": false,"body":"'"$RELEASE_BODY\n\nFor installation instructions, please visit https://docs.sigit.io/#/"'"}' -X PATCH --header 'Content-Type: application/json' -k https://git.nostrdev.com/sigit/sigit.io/releases/$RELEASE_ID?access_token=${{ secrets.RELEASE_TOKEN }}
          echo "Uploading assets"
          URL="https://git.nostrdev.com/api/v1/repos/sigit/sigit.io/releases/$RELEASE_ID/assets?access_token=${{ secrets.RELEASE_TOKEN }}"
          curl -k $URL -F attachment=@dist.zip