name: Upload releases

on:
  release:
    types:
      - created

permissions:
  contents: write

env:
  RUSTFLAGS: -Ctarget-feature=+crt-static
  VCPKG_COMMIT: ab2977be50c702126336e5088f4836060733c899

jobs:
  build_windows:
    runs-on: windows-2022
    strategy:
      fail-fast: false
      matrix:
        include:
          - arch: x64
            platform: x64
            vcpkg_triplet: x64-windows-static
            rust_target: x86_64-pc-windows-msvc
            wix_arch: x64
            suffix: ""
            gpac_install: "C:\\Program Files\\GPAC"
            outdir: "x64/"
          - arch: x86
            platform: Win32
            vcpkg_triplet: x86-windows-static
            rust_target: i686-pc-windows-msvc
            wix_arch: x86
            suffix: "_x86"
            gpac_install: "C:\\Program Files (x86)\\GPAC"
            outdir: ""
    steps:
    - name: Check out repository
      uses: actions/checkout@v6
    - name: Get the version
      id: get_version
      run: |
        # Extract version from tag, strip 'v' prefix and everything after first dash
        VERSION=${GITHUB_REF/refs\/tags\/v/}
        VERSION=${VERSION%%-*}
        # Save display version for filenames (e.g., 0.96.1)
        echo ::set-output name=DISPLAY_VERSION::$VERSION
        # Count dots to determine version format
        DOTS="${VERSION//[^.]}"
        PART_COUNT=$((${#DOTS} + 1))
        # MSI requires 4-part version (major.minor.build.revision)
        if [ "$PART_COUNT" -eq 2 ]; then
          MSI_VERSION="${VERSION}.0.0"
        elif [ "$PART_COUNT" -eq 3 ]; then
          MSI_VERSION="${VERSION}.0"
        else
          MSI_VERSION="${VERSION}"
        fi
        echo ::set-output name=VERSION::$MSI_VERSION
      shell: bash
    - name: Setup MSBuild.exe
      uses: microsoft/setup-msbuild@v3.0.0
      with:
        msbuild-architecture: x64
    - name: Install gpac
      run: choco install gpac --version 2.4.0 ${{ matrix.arch == 'x86' && '--forcex86' || '' }}
    # Use lukka/run-vcpkg for better caching
    - name: Setup vcpkg
      uses: lukka/run-vcpkg@v11
      id: runvcpkg
      with:
        vcpkgGitCommitId: ${{ env.VCPKG_COMMIT }}
        vcpkgDirectory: ${{ github.workspace }}/vcpkg
        vcpkgJsonGlob: 'windows/vcpkg.json'

    # Cache vcpkg installed packages separately for faster restores
    - name: Cache vcpkg installed packages
      id: vcpkg-installed-cache
      uses: actions/cache@v5
      with:
        path: ${{ github.workspace }}/vcpkg/installed
        key: vcpkg-installed-${{ runner.os }}-${{ matrix.vcpkg_triplet }}-${{ env.VCPKG_COMMIT }}-${{ hashFiles('windows/vcpkg.json') }}
        restore-keys: |
          vcpkg-installed-${{ runner.os }}-${{ matrix.vcpkg_triplet }}-${{ env.VCPKG_COMMIT }}-

    - name: Install dependencies
      if: steps.vcpkg-installed-cache.outputs.cache-hit != 'true'
      run: ${{ github.workspace }}/vcpkg/vcpkg.exe install --triplet ${{ matrix.vcpkg_triplet }} --x-install-root ${{ github.workspace }}/vcpkg/installed/
      working-directory: windows
    - name: Setup Rust toolchain
      uses: dtolnay/rust-toolchain@stable
      with:
        targets: ${{ matrix.rust_target }}

    # Cache Cargo registry
    - name: Cache Cargo registry
      uses: actions/cache@v5
      with:
        path: |
          ~/.cargo/registry
          ~/.cargo/git
        key: ${{ runner.os }}-cargo-registry-${{ hashFiles('**/Cargo.lock') }}
        restore-keys: |
          ${{ runner.os }}-cargo-registry-

    - name: Install Win 10 SDK
      uses: ilammy/msvc-dev-cmd@v1
      with:
        arch: ${{ matrix.arch }}
    - name: build Release-Full
      env:
        LIBCLANG_PATH: "C:\\Program Files\\LLVM\\lib"
        LLVM_CONFIG_PATH: "C:\\Program Files\\LLVM\\bin\\llvm-config"
        CARGO_TARGET_DIR: "..\\..\\windows"
        BINDGEN_EXTRA_CLANG_ARGS: -fmsc-version=0
        VCPKG_ROOT: ${{ github.workspace }}/vcpkg
        VCPKG_DEFAULT_TRIPLET: ${{ matrix.vcpkg_triplet }}
      run: msbuild ccextractor.sln /p:Configuration=Release-Full /p:Platform=${{ matrix.platform }} /p:GpacDir="${{ matrix.gpac_install }}"
      working-directory: ./windows
    - name: Copy files to directory for installer
      run: mkdir installer; cp ./${{ matrix.outdir }}Release-Full/ccextractorwinfull.exe ./installer; cp ./${{ matrix.outdir }}Release-Full/*.dll ./installer
      working-directory: ./windows
    - name: Download tessdata for OCR support
      run: |
        mkdir -p ./installer/tessdata
        # Download English traineddata from tessdata_fast (smaller, faster, good for most use cases)
        Invoke-WebRequest -Uri "https://github.com/tesseract-ocr/tessdata_fast/raw/main/eng.traineddata" -OutFile "./installer/tessdata/eng.traineddata"
        # Download OSD (Orientation and Script Detection) for automatic script detection
        Invoke-WebRequest -Uri "https://github.com/tesseract-ocr/tessdata_fast/raw/main/osd.traineddata" -OutFile "./installer/tessdata/osd.traineddata"
      working-directory: ./windows
    - name: install WiX
      run: dotnet tool uninstall --global wix; dotnet tool install --global wix --version 6.0.2 && wix extension add -g WixToolset.UI.wixext/6.0.2
    - name: Make sure WiX works
      run: wix --version && wix extension list -g
    - name: Download Flutter GUI
      run: ((Invoke-WebRequest -UseBasicParsing https://api.github.com/repos/CCExtractor/ccextractorfluttergui/releases/latest).Content | ConvertFrom-Json).assets | ForEach-Object {if ($_.name -eq "windows.zip") { Invoke-WebRequest -UseBasicParsing -Uri $_.browser_download_url -OutFile windows.zip}}
      working-directory: ./windows
    - name: Display contents of dir
      run: ls
      working-directory: ./windows
    - name: Unzip Flutter GUI
      run: Expand-Archive -Path ./windows.zip -DestinationPath ./installer -Force
      working-directory: ./windows
    - name: Display installer folder contents
      run: Get-ChildItem -Recurse ./installer
      working-directory: ./windows
    - name: Create portable zip
      run: Compress-Archive -Path ./installer/* -DestinationPath ./CCExtractor.${{ steps.get_version.outputs.DISPLAY_VERSION }}${{ matrix.suffix }}_win_portable.zip
      working-directory: ./windows
    - name: Build installer
      run:  wix build -arch ${{ matrix.wix_arch }} -ext WixToolset.UI.wixext -d "AppVersion=${{ steps.get_version.outputs.VERSION }}" -o CCExtractor.${{ steps.get_version.outputs.DISPLAY_VERSION }}${{ matrix.suffix }}.msi installer.wxs CustomUI.wxs
      working-directory: ./windows
    - name: Upload as asset
      uses: AButler/upload-release-assets@v3.0
      with:
        files: './windows/CCExtractor.${{ steps.get_version.outputs.DISPLAY_VERSION }}${{ matrix.suffix }}.msi;./windows/CCExtractor.${{ steps.get_version.outputs.DISPLAY_VERSION }}${{ matrix.suffix }}_win_portable.zip'
        repo-token: ${{ secrets.GITHUB_TOKEN }}
  create_linux_package:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v6
        with:
          path: ./ccextractor
      - name: Get the version
        id: get_version
        run: |
          VERSION=${GITHUB_REF/refs\/tags\/v/}
          VERSION=${VERSION%%-*}
          echo ::set-output name=DISPLAY_VERSION::$VERSION
      - name: Create .tar.gz without git and windows folders
        run: tar -pczf ./ccextractor.${{ steps.get_version.outputs.DISPLAY_VERSION }}.tar.gz --exclude "ccextractor/windows" --exclude "ccextractor/.git" ccextractor
      - name: Upload as asset
        uses: AButler/upload-release-assets@v3.0
        with:
          files: './ccextractor.${{ steps.get_version.outputs.DISPLAY_VERSION }}.tar.gz'
          repo-token: ${{ secrets.GITHUB_TOKEN }}
