name: upload

on:
  push:
    branches: [master]
  release:
    types: [published]

jobs:
  build-static:
    name: build static binary
    runs-on: ubuntu-latest
    container:
      image: ghcr.io/linux-nvme/debian:latest
    outputs:
      VERSION: ${{ steps.build.outputs.VERSION }}
    steps:
      - uses: actions/checkout@v5
        with:
          fetch-depth: 0

      - name: build
        id: build
        run: |
          git config --global --add safe.directory "$GITHUB_WORKSPACE"
          VERSION="$(git describe --always --abbrev=12 --dirty)"
          echo "VERSION=${VERSION}" >> $GITHUB_OUTPUT
          echo $VERSION

          scripts/build.sh static
          mkdir upload
          cp .build-ci/nvme upload/nvme-cli-latest-x86_64
          if [ "${GITHUB_EVENT_NAME}" = "release" ]; then
            cp .build-ci/nvme "upload/nvme-cli-${VERSION}-x86_64"
          fi

      - uses: actions/upload-artifact@v5
        name: upload artifacts to github
        with:
          name: nvme-cli
          path: upload/*

  upload-test-binary:
    name: upload test binary
    runs-on: ubuntu-latest
    needs: build-static
    if: ${{ github.event_name == 'push' || github.event_name == 'release' }}
    steps:
      - uses: actions/download-artifact@v6
        with:
          name: nvme-cli
          path: upload

      - name: FTP Deployer
        uses: sand4rt/ftp-deployer@v1.8
        with:
          sftp: true
          host: ${{ secrets.SFTP_SERVER }}
          port: 22
          username: ${{ secrets.SFTP_USERNAME }}
          password: ${{ secrets.SFTP_PASSWORD }}
          remote_folder: '/upload'
          local_folder: upload
          cleanup: false
          include: '[ "nvme-cli-*" ]'
          exclude: '[".github/**", ".git/**", "*.env"]'

  upload-release-assets:
    name: upload GitHub release assets
    runs-on: ubuntu-latest
    needs: build-static
    env:
      VERSION: ${{ needs.build-static.outputs.VERSION }}
    if: ${{ github.event_name == 'release' }}
    steps:
      - uses: actions/download-artifact@v6
        with:
          name: nvme-cli
          path: upload
      - name: upload versioned binary
        uses: actions/upload-release-asset@v1
        with:
          upload_url: ${{ github.event.release.upload_url }}
          asset_path: upload/nvme-cli-${{ env.VERSION }}-x86_64
          asset_name: nvme-cli-${{ env.VERSION }}-x86_64
          asset_content_type: application/octet-stream
