name: Build iso when a new version is pushed
run-name: iso building
on:
  push:
    branches:
      - 'master'

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - name: get repo
        uses: actions/checkout@v4.2.2

      - name: install nix
        uses: https://github.com/cachix/install-nix-action@v31

      - name: install go
        uses: https://github.com/actions/setup-go@v4
        with:
          go-version: '>=1.20.1'

      - name: build iso
        run: make iso

      - name: get commit tag
        id: vars
        run: echo "TAG=$(git rev-parse --short HEAD)" >> $GITHUB_OUTPUT

      - name: create tag
        run: |
          git config user.name "gitea-actions"
          git config user.email "actions@gitea.com"
          git tag ${{steps.vars.outputs.TAG}}
          git push origin ${{steps.vars.outputs.TAG}}
      
      - name: create release
        run: |
          AUTH_TOKEN=${{secrets.RELEASE_TOKEN}}
          TAG_NAME=${{steps.vars.outputs.TAG}}
          owner=tom
          repo=nix-config
          set -e
          release_create_res=$(curl -X POST -H "Authorization: token $AUTH_TOKEN" -H "content-type: application/json" -d "{\"tag_name\":\"$TAG_NAME\",\"name\":\"$TAG_NAME\"}" "https://git.tmoron.fr/api/v1/repos/$owner/$repo/releases" 2>/dev/null)
          
          release_id=$(echo $release_create_res | jq -r .id)
          echo $release_id
          
          if [ $release_id == "null" ]; then
          	echo error
          	exit 1
          fi
          
          file_send_res=$(curl \
          	"https://git.tmoron.fr/api/v1/repos/$owner/$repo/releases/$release_id/assets?name=nixos.iso"\
          	-H "Authorization: token $AUTH_TOKEN"\
          	-H "accept: application/json"\
          	-H "Content-Type: multipart/form-data"\
          	-F "attachment=@nixos.iso" 2>/dev/null)
          echo $file_send_res
