name: Release ISOs

on:
  workflow_dispatch:
    workflows: ["CI"]
    types:
      - completed
    branches: ["main"]

jobs:
  build-isos:
    runs-on: nix
    env:
      NIXPKGS_ALLOW_UNFREE: "1"
    steps:
      - name: Checkout
        run: git clone https://git.cyperpunk.de/DerGrumpf/cyper-nix.git .

      - name: Build ISOs
        run: |
          nix build .#packages.x86_64-linux.cyper-desktop-iso --out-link result-desktop
          nix build .#packages.x86_64-linux.cyper-controller-iso --out-link result-controller
          nix build .#packages.x86_64-linux.cyper-proxy-iso --out-link result-proxy
          nix build .#packages.x86_64-linux.cyper-node-1-iso --out-link result-node-1
          nix build .#packages.x86_64-linux.cyper-node-2-iso --out-link result-node-2

      - name: Create release and upload ISOs
        run: |
          TAG="iso-$(date +%Y%m%d-%H%M%S)"
          COMMIT=$(git -C . rev-parse --short HEAD)

          RELEASE=$(curl -s -X POST \
            -H "Authorization: token ${{ secrets.CI_TOKEN }}" \
            -H "Content-Type: application/json" \
            -d "{\"tag_name\":\"${TAG}\",\"name\":\"ISOs ${TAG}\",\"body\":\"Automated ISO build from commit ${COMMIT}\"}" \
            "https://git.cyperpunk.de/api/v1/repos/DerGrumpf/cyper-nix/releases")

          RELEASE_ID=$(echo $RELEASE | grep -o '"id":[0-9]*' | head -1 | cut -d: -f2)

          for result in result-desktop result-controller result-proxy result-node-1 result-node-2; do
            iso=$(find $result/iso -name "*.iso" | head -1)
            curl -s -X POST \
              -H "Authorization: token ${{ secrets.CI_TOKEN }}" \
              -F "attachment=@${iso};filename=${result}.iso" \
              "https://git.cyperpunk.de/api/v1/repos/DerGrumpf/cyper-nix/releases/${RELEASE_ID}/assets"
          done
