name: Create Release

on:
  push:
    # Note: It's branch main OR tags v*, not AND! Tags are not per-branch.
    branches:
      - main
    tags:
      - "v*"

jobs:
  Build-And-Test-Linux:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3

      - name: Use last commit hash as build version for the developer build.
        if: "startsWith(github.ref, 'refs/heads/')"
        run: echo "build_version=${GITHUB_SHA}" >> $GITHUB_ENV

      - name: Use tag name as build version for the release build.
        if: startsWith(github.ref, 'refs/tags/v')
        run: echo "build_version=${GITHUB_REF#refs/tags/v}" >> $GITHUB_ENV

      # This flow should not be used for pull requests. However the section
      # below might be useful for testing purposes.
      - name: Use last commit hash as build version for the pull request
        if: startsWith(github.ref, 'refs/pull')
        run: echo "build_version=${GITHUB_SHA}" >> $GITHUB_ENV

      - name: Replace CDC_BUILD_VERSION
        run: |
          if grep -q "DCDC_BUILD_VERSION=DEV" "common/BUILD"; then
              sed -i 's/DCDC_BUILD_VERSION=DEV/DCDC_BUILD_VERSION=${{ env.build_version }}/g' common/BUILD
          else
              echo "CDC_BUILD_VERSION was moved out from common/BUILD file."
              echo "Please edit create_release.yaml workflow."
              exit 1
          fi

      - name: Initialize submodules
        run: git submodule update --init --recursive

      - name: Create timestamp
        run: |
          printf -v date '%(%Y-%m)T' -1
          echo "date=$date" >> $GITHUB_ENV

      - name: Restore build cache
        uses: actions/cache@v3
        with:
          path: bazel-cache
          key: ${{ runner.os }}-bazel-cache-opt-${{ env.date }}

      - name: Build (opt)
        run: |
          bazel build --config=linux --disk_cache=bazel-cache --compilation_mode=opt --linkopt=-Wl,--strip-all --copt=-fdata-sections --copt=-ffunction-sections --linkopt=-Wl,--gc-sections \
            //cdc_fuse_fs //cdc_rsync_server

      - name: Test (opt)
        run: |
          bazel test --config=linux --disk_cache=bazel-cache --compilation_mode=opt --linkopt=-Wl,--strip-all --copt=-fdata-sections --copt=-ffunction-sections --linkopt=-Wl,--gc-sections \
                     --test_output=errors --local_test_jobs=1  \
                     -- //... -//third_party/... -//cdc_rsync_server:file_finder_test

      # The artifact collector doesn't like the fact that bazel-bin is a symlink.
      - name: Copy artifacts
        run: |
          mkdir artifacts
          cp bazel-bin/cdc_fuse_fs/cdc_fuse_fs artifacts
          cp bazel-bin/cdc_rsync_server/cdc_rsync_server artifacts
          cp bazel-bin/external/com_github_fuse/libfuse.so artifacts

      - name: Upload artifacts
        uses: actions/upload-artifact@v3
        with:
          name: Linux-Artifacts
          path: artifacts

  Build-And-Test-Windows:
    runs-on: windows-2019
    steps:
      - uses: actions/checkout@v3

      - name: Use last commit hash as build version for the developer build.
        if: "startsWith(github.ref, 'refs/heads/')"
        run: |
          $build_version="${{ github.sha }}"
          echo "build_version=$build_version" >> $env:GITHUB_ENV

      - name: Use tag name as build version for the release build.
        if: "startsWith(github.ref, 'refs/tags/v')"
        run: |
          $build_version="${{ github.ref }}".replace("refs/tags/v", "")
          echo "build_version=$build_version" >> $env:GITHUB_ENV

      # This flow should not be used for pull requests. However the section
      # below might be useful for testing purposes.
      - name: Use last commit hash as build version for the pull request
        if: startsWith(github.ref, 'refs/pull')
        run: |
          $build_version="${{ github.sha }}"
          echo "build_version=$build_version" >> $env:GITHUB_ENV

      - name: Replace CDC_BUILD_VERSION
        run: |
          $cdc_version = Select-String -Path common/BUILD -Pattern "DCDC_BUILD_VERSION=DEV"
          if ($cdc_version -ne $null) {
              $build_file = Get-Content -path common/BUILD -Raw
              $build_file = $build_file -replace 'DCDC_BUILD_VERSION=DEV','DCDC_BUILD_VERSION=${{ env.build_version }}'
              $build_file | Set-Content -Path common/BUILD
          }
          else {
              Write-Host "CDC_BUILD_VERSION was moved out from common/BUILD file."
              Write-Host "Please edit create_release.yaml workflow."
              exit 1
          }

      - name: Initialize submodules
        run: git submodule update --init --recursive

      - name: Create timestamp
        run: |
          $date = Get-Date -Format "yyyy-MM"
          echo "date=$date" >> $env:GITHUB_ENV

      - name: Restore build cache
        uses: actions/cache@v3
        with:
          path: bazel-cache
          key: ${{ runner.os }}-bazel-cache-opt-${{ env.date }}

      - name: Build (opt)
        run: |
          bazel build --config=windows --disk_cache=bazel-cache --compilation_mode=opt --copt=/GL `
                       //cdc_rsync //cdc_stream //tests_common //tests_cdc_stream //tests_cdc_rsync

      - name: Test (opt)
        run: |
          bazel-bin\tests_common\tests_common.exe
          bazel-bin\tests_cdc_stream\tests_cdc_stream.exe
          bazel-bin\tests_cdc_rsync\tests_cdc_rsync.exe
          bazel test --config=windows --disk_cache=bazel-cache --compilation_mode=opt --copt=/GL --test_output=errors --local_test_jobs=1 `
            //cdc_fuse_fs/... `
            //cdc_rsync/... `
            //cdc_rsync/base/... `
            //cdc_rsync_server/... `
            //cdc_stream/... `
            //common/... `
            //data_store/... `
            //fastcdc/... `
            //manifest/... `
            //metrics/...

      # The artifact collector doesn't like the fact that bazel-bin is a symlink.
      - name: Copy artifacts
        run: |
          mkdir artifacts
          mkdir artifacts\docs
          cp bazel-bin/cdc_rsync/cdc_rsync.exe artifacts
          cp bazel-bin/cdc_rsync_server/cdc_rsync_server.exe artifacts
          cp bazel-bin/cdc_stream/cdc_stream.exe artifacts
          cp LICENSE artifacts
          cp README.md artifacts
          cp docs\* artifacts\docs

      - name: Upload artifacts
        uses: actions/upload-artifact@v3
        with:
          name: Windows-Artifacts
          path: artifacts

  Create-Release:
    runs-on: ubuntu-latest
    needs: [Build-And-Test-Windows, Build-And-Test-Linux]
    steps:
      - name: Download artifacts
        uses: actions/download-artifact@v3

      - name: Zip binaries
        run: |
          # The ref resolves to "main" for latest and e.g. "v0.1.0" for tagged.
          REF=${GITHUB_REF#refs/*/}
          # For pull requests, this is e.g. '70/merge', so replace / with -.
          REF=${REF/\//-}
          BINARIES_ZIP_NAME=cdc-file-transfer-binaries-$REF-x64.zip
          echo "BINARIES_ZIP_NAME=$BINARIES_ZIP_NAME" >> $GITHUB_ENV
          zip -j $BINARIES_ZIP_NAME Windows-Artifacts/* Linux-Artifacts/*

      - name: Publish latest release
        if: "!startsWith(github.ref, 'refs/tags/v')"
        uses: "marvinpinto/action-automatic-releases@latest"
        with:
          repo_token: "${{ secrets.GITHUB_TOKEN }}"
          automatic_release_tag: "latest"
          prerelease: true
          title: "Development Build"
          files: ${{ env.BINARIES_ZIP_NAME }}

      - name: Publish tagged release
        if: startsWith(github.ref, 'refs/tags/v')
        uses: "marvinpinto/action-automatic-releases@latest"
        with:
          repo_token: "${{ secrets.GITHUB_TOKEN }}"
          prerelease: false
          files: ${{ env.BINARIES_ZIP_NAME }}
