name: Nightly Build
on:
  push:
    branches:
      - main

permissions:
  contents: write

env:
  MISE_VERSION: "2026.3.7"

jobs:
  nightly:
    # Run on macOS to be able to build the fsevent dependency required by compose on macOS.
    runs-on: macos-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
        with:
          fetch-depth: 0

      - name: Install Mise
        uses: jdx/mise-action@1648a7812b9aeae629881980618f079932869151 # v4.0.1
        with:
          version: ${{ env.MISE_VERSION }}
      - name: Reset changes in mise.lock after fresh mise install
        run: git checkout mise.lock

      - name: Cache Go build and module cache
        uses: actions/cache@668228422ae6a00e4ad889ee87cd7109ec5666a7 # v5.0.4
        with:
          path: |
            ~/Library/Caches/go-build
            ~/go/pkg/mod
          key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}-${{ hashFiles('**/*.go') }}
          restore-keys: |
            ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}-
            ${{ runner.os }}-go-

      - name: Run GoReleaser snapshot
        run: goreleaser release --snapshot --clean
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

      - name: Delete existing nightly release
        run: gh release delete nightly --yes --cleanup-tag || true
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

      - name: Create nightly release
        run: |
          COMMIT=$(git rev-parse --short HEAD)
          DATE=$(date -u '+%Y-%m-%d %H:%M UTC')
          RELEASE_NOTES=$(cat <<EOF
          Built from \`main\` at ${COMMIT} on ${DATE}.

          The commands below show how to install the nightly version of uncloud.

          > **Warning**: These are nightly development builds and may be unstable.

          **Install uncloud CLI:**

          \`\`\`
          curl -fsS https://get.uncloud.run/install.sh | VERSION=nightly sh
          \`\`\`

          **Initialize a cluster or add a machine:**

          \`\`\`
          uc machine init --version nightly user@host
          uc machine add  --version nightly user@host
          \`\`\`

          **Upgrade machine daemon:**

          \`\`\`
          ARCH=\$(uname -m | sed 's/x86_64/amd64/;s/aarch64/arm64/')
          curl -fsSL -o uncloudd.tar.gz https://github.com/psviderski/uncloud/releases/download/nightly/uncloudd_linux_\${ARCH}.tar.gz
          tar -xf uncloudd.tar.gz
          sudo install uncloudd /usr/local/bin/uncloudd
          rm uncloudd uncloudd.tar.gz
          sudo systemctl restart uncloud
          \`\`\`

          EOF
          )

          gh release create nightly \
            --title "Nightly Build" \
            --notes "${RELEASE_NOTES}" \
            --prerelease \
            --target ${{ github.sha }} \
            dist/*.tar.gz dist/checksums.txt
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

    timeout-minutes: 30
