name: VS2022

on: 
  push:
    paths-ignore:
      - '.gitignore'
      - '.gitattributes'
      - '**.cmd'
      - '**.md'
      - 'AUTHORS'
      - 'NEWS'
      - 'ChangeLog'
  pull_request:
    paths-ignore:
      - '.gitignore'
      - '.gitattributes'
      - '**.cmd'
      - '**.md'
      - 'AUTHORS'
      - 'NEWS'
      - 'ChangeLog'

env:
  WDK_URL: https://go.microsoft.com/fwlink/p/?LinkID=253170
  LIBUSB0_URL: https://github.com/mcuee/libusb-win32/releases/download/release_1.4.0.0/libusb-win32-bin-1.4.0.0.zip
  LIBUSBK_URL: https://github.com/mcuee/libusbk/releases/download/V3.1.0.0/libusbK-3.1.0.0-bin.7z
  SOLUTION_FILE_PATH: ./libwdi.sln
  BUILD_MACROS: '"WDK_DIR=\"../wdk/Windows Kits/8.0\";LIBUSB0_DIR=\"../libusb0\";LIBUSBK_DIR=\"../libusbk/bin\""'

jobs:
  VS2022-Build:
    runs-on: windows-latest

    steps:
    - name: Checkout repository
      uses: actions/checkout@v4
      with:
        fetch-depth: 0
        submodules: recursive

    - name: Download support files
      shell: cmd
      run: |
        curl -L ${{ env.WDK_URL }} -o wdk-redist.msi
        curl -L ${{ env.LIBUSB0_URL }} -o libusb0-redist.zip
        curl -L ${{ env.LIBUSBK_URL }} -o libusbk-redist.7z
        msiexec /a wdk-redist.msi /qn TARGETDIR=%CD%\wdk
        7z x libusb0-redist.zip
        7z x libusbk-redist.7z
        del *.zip
        del *.7z
        move libusb-win32* libusb0
        move libusbK* libusbk

    - name: Add MSBuild to PATH
      uses: microsoft/setup-msbuild@v2

    - name: Build
      shell: cmd
      run: |
        for %%P in (Win32 x64) do (
          for %%B in (Debug Release) do (
            msbuild ${{ env.SOLUTION_FILE_PATH }} /m /p:Configuration=%%B,Platform=%%P,BuildMacros=${{ env.BUILD_MACROS }}
          )
        )

    - name: Upload artifacts
      uses: actions/upload-artifact@v4
      if: ${{ github.event_name == 'push' }}
      with:
        name: VS2022
        path: ./*/*/examples/*.exe

    - name: Display SHA-256
      if: ${{ github.event_name == 'push' }}
      run: sha256sum ./*/*/examples/*.exe

    - name: Compress release-ready version of Zadig
      uses: crazy-max/ghaction-upx@v3
      if: startsWith(github.ref, 'refs/tags/')
      with:
        version: latest
        files: ./Win32/Release/examples/zadig.exe
        args: --lzma --best

    - name: Rename release-ready version of Zadig
      if: startsWith(github.ref, 'refs/tags/')
      shell: cmd
      run: |
        for /f "tokens=3" %%i in ('findstr FileVersion examples\zadig.rc') do set "ver=%%i"
        set ver=%ver:"=%
        for /f "tokens=1,2 delims=." %%i in ("%ver%") do set "ZADIG_VERSION=%%i.%%j"
        copy Win32\Release\examples\zadig.exe zadig-%ZADIG_VERSION%.exe
        sha256sum zadig-*.exe

    - name: Upload release-ready version of Zadig
      uses: actions/upload-artifact@v4
      if: startsWith(github.ref, 'refs/tags/')
      with:
        name: Zadig
        path: ./zadig-*.exe
