name: Steam Upload

on:
  release:
    types:
    - published
  workflow_dispatch:
    inputs:
      tag:
        description: 'Tag to fetch and upload (nightly if none)'
        required: false
      win_url_override:
        description: 'Windows build to use (.zip only)'
        required: false
      mac_url_override:
        description: 'Mac build to use (.dmg only)'
        required: false
      mac_arm_url_override:
        description: 'Mac ARM build to use (.dmg only)'
        required: false
  schedule:
  - cron: 0 0 * * *

env:
  WORKFLOW_ID: 583765
  GIT_NIGHTLY_BRANCH: master
  STEAM_NIGHTLY_BRANCH: nightly
  STEAM_STABLE_BRANCH: staging
  STEAM_BETA_BRANCH: beta_staging
  STEAM_PLAYTEST_BRANCH: staging
  SEVENZIP_HASH: 5290409e7bbe2f133d0bd7e7482548678157ea2be276b0f9cb440600f4be9a2d

jobs:
  upload:
    name: Steam upload
    runs-on: ubuntu-20.04
    if: github.repository_owner == 'obsproject'

    steps:
    - name: Checkout
      uses: actions/checkout@v3
      with:
        path: source

      # The 7-Zip version available in the default ubuntu repos (p7zip) is wildly out-of-date and does not properly support DMG files.
    - name: Setup 7-Zip
      run: |
        mkdir 7z && cd 7z
        curl -s https://www.7-zip.org/a/7z2200-linux-x64.tar.xz -o 7z.tar.xz
        
        if [[ '${{ env.SEVENZIP_HASH }}' != "$(sha256sum 7z.tar.xz | cut -d " " -f 1)" ]]; then
            echo "7-Zip Download hash does not match!"
            exit 1
        fi
        
        tar -xJf 7z.tar.xz
        echo "$(pwd)" >> $GITHUB_PATH

    - name: Get build information
      id: build-info
      run: |
        EVENT='${{ github.event_name }}'
        if [[ ${EVENT} == 'release' || ( ${EVENT} == 'workflow_dispatch' && -n '${{ github.event.inputs.tag }}') ]]; then
            if [[ ${EVENT} == "release" ]]; then
                DESC='${{ github.event.release.tag_name }}'
                if [[ '${{ github.event.release.prerelease }}' == 'true' ]]; then
                  BRANCH='${{ env.STEAM_BETA_BRANCH }}'
                else
                  BRANCH='${{ env.STEAM_STABLE_BRANCH }}'
                fi
                ASSETS_URL='${{ github.event.release.assets_url }}'
            else
                RELEASE="$(curl -s '${{ github.api_url }}/repos/obsproject/obs-studio/releases/tags/${{ github.event.inputs.tag }}')"

                DESC="$(jq -r '.tag_name' <<< ${RELEASE})"
                if [[ "$(jq -r '.prerelease' <<< ${RELEASE})" == 'true' ]]; then
                  BRANCH='${{ env.STEAM_BETA_BRANCH }}'
                else
                  BRANCH='${{ env.STEAM_STABLE_BRANCH }}'
                fi
                ASSETS_URL="$(jq -r '.assets_url' <<< ${RELEASE})"
            fi

            ASSETS="$(curl -s "${ASSETS_URL}")"
            WIN_ASSET_URL="$(jq -r '.[] | select(.name|test(".*x64.zip")) .browser_download_url' <<< ${ASSETS})"
            MAC_ASSET_URL="$(jq -r '.[] | select(.name|test(".*x86_64.*.dmg")) .browser_download_url' <<< ${ASSETS})"
            MAC_ARM_ASSET_URL="$(jq -r '.[] | select(.name|test(".*arm64.*.dmg")) .browser_download_url' <<< ${ASSETS})"
            TYPE='release'
        else
            BRANCH='${{ env.STEAM_NIGHTLY_BRANCH }}'
            BUILDS="$(curl -s '${{ github.api_url }}/repos/obsproject/obs-studio/actions/workflows/${{ env.WORKFLOW_ID }}/runs?per_page=1&event=push&status=success&branch=${{ env.GIT_NIGHTLY_BRANCH }}')"
            ARTIFACTS_URL="$(jq -r '.workflow_runs[].artifacts_url' <<< ${BUILDS})"
            DESC="g$(jq -r '.workflow_runs[].head_sha' <<< "${BUILDS}" | cut -c1-9)"

            ARTIFACTS="$(curl -s ${ARTIFACTS_URL})"
            WIN_ASSET_URL="$(jq -r '.artifacts[] | select(.name|test(".*windows-x64.*")) .archive_download_url' <<< ${ARTIFACTS})"
            MAC_ASSET_URL="$(jq -r '.artifacts[] | select(.name|test(".*macos-x86_64.*")) .archive_download_url' <<< ${ARTIFACTS})"
            MAC_ARM_ASSET_URL="$(jq -r '.artifacts[] | select(.name|test(".*macos-arm64.*")) .archive_download_url' <<< ${ARTIFACTS})"
            TYPE='nightly'
        fi

        # Apply overrides from workflow_dispatch
        if [[ ${EVENT} == 'workflow_dispatch' ]]; then
            if [[ -n '${{ github.event.inputs.win_url_override }}' ]]; then
                WIN_ASSET_URL='${{ github.event.inputs.win_url_override }}'
            fi

            if [[ -n '${{ github.event.inputs.mac_url_override }}' ]]; then
                MAC_ASSET_URL='${{ github.event.inputs.mac_url_override }}'
            fi

            if [[ -n '${{ github.event.inputs.mac_arm_url_override }}' ]]; then
                MAC_ARM_ASSET_URL='${{ github.event.inputs.mac_arm_url_override }}'
            fi
        fi

        if [[ -z ${WIN_ASSET_URL} || -z ${MAC_ASSET_URL} || -z ${MAC_ARM_ASSET_URL} ]]; then
            echo "Missing at least one asset URL!"
            exit 1
        fi

        # set env variables for subsequent steps
        echo "type=${TYPE}" >> $GITHUB_OUTPUT
        echo "branch=${BRANCH}" >> $GITHUB_OUTPUT
        echo "desc=${DESC}" >> $GITHUB_OUTPUT
        echo "win_url=${WIN_ASSET_URL}" >> $GITHUB_OUTPUT
        echo "mac_intel_url=${MAC_ASSET_URL}" >> $GITHUB_OUTPUT
        echo "mac_arm_url=${MAC_ARM_ASSET_URL}" >> $GITHUB_OUTPUT

    - name: Restore build cache
      id: cache
      uses: actions/cache@v3
      with:
        path: ${{ github.workspace }}/steam/build
        key: ${{ steps.build-info.outputs.branch }}-${{ steps.build-info.outputs.desc }}
        # Using "restore-keys" will restore the most recent cache for the branch, even if the exact cache doesn't exist.
        # This doesn't set cache-hit to true so it won't skip the upload for nightlies.
        restore-keys: ${{ steps.build-info.outputs.branch }}

    - name: Determine if Steam upload should run
      # If the nightly build has already been uploaded and thus a cache exists skip this and the following steps.
      # Steam does not prevent us from uploading duplicate builds so this would just pollute the dashboard.
      # This is a bit of a hack and can fail to work if our cache has been evicted or we somehow have no commits for 7 days,
      # but it's better than nothing!
      id: should-run
      run: |
        if [[ '${{ steps.build-info.outputs.type }}' == 'release' || '${{ steps.cache.outputs.cache-hit }}' != 'true' ]]; then
            echo "result=true" >> $GITHUB_OUTPUT
            if [[ '${{ steps.build-info.outputs.branch }}' == '${{ env.STEAM_BETA_BRANCH }}' ]]; then
                echo "result_playtest=true" >> $GITHUB_OUTPUT
            else
                echo "result_playtest=false" >> $GITHUB_OUTPUT
            fi
        else
            echo "result=false" >> $GITHUB_OUTPUT
            echo "result_playtest=false" >> $GITHUB_OUTPUT
        fi

    - name: Download and prepare builds
      if: steps.should-run.outputs.result == 'true'
      run: |
        echo "::group::Download Windows build"
        if [[ '${{ steps.build-info.outputs.win_url }}' == *'api.github.com'* ]]; then
            curl -L -H 'Authorization: Bearer ${{ secrets.GITHUB_TOKEN }}' '${{ steps.build-info.outputs.win_url }}' -o windows.zip
        else
            curl -L '${{ steps.build-info.outputs.win_url }}' -o windows.zip
        fi
        echo "::endgroup::"

        echo "::group::Download Mac builds"
        if [[ '${{ steps.build-info.outputs.mac_intel_url }}' == *'api.github.com'* ]]; then
            curl -L -H 'Authorization: Bearer ${{ secrets.GITHUB_TOKEN }}' '${{ steps.build-info.outputs.mac_intel_url }}' -o mac_x86.dmg.zip
        else
            curl -L '${{ steps.build-info.outputs.mac_intel_url }}' -o mac_x86.dmg
        fi

        if [[ '${{ steps.build-info.outputs.mac_arm_url }}' == *'api.github.com'* ]]; then
            curl -L -H 'Authorization: Bearer ${{ secrets.GITHUB_TOKEN }}' '${{ steps.build-info.outputs.mac_arm_url }}' -o mac_arm64.dmg.zip
        else
            curl -L '${{ steps.build-info.outputs.mac_arm_url }}' -o mac_arm64.dmg
        fi
        echo "::endgroup::"

        mkdir -p steam && cd steam

        echo "::group::Extract and prepare Win64"
        mkdir steam-windows
        (
            cd steam-windows
            unzip ../../windows.zip
            # CI builds can be double-zipped
            if compgen -G "*.zip" > /dev/null; then
                unzip *.zip
                rm *.zip
            fi
            # copy install scripts and create sentinel file
            cp -r ../../source/CI/steam/scripts_windows scripts
            touch disable_updater
        )
        echo "::endgroup::"

        echo "::group::Extract macOS (x86)"
        mkdir -p steam-macos/x86
        # CI builds are zipped
        if [[ -f ../mac_x86.dmg.zip ]]; then
            unzip ../mac_x86.dmg.zip
            # 7-Zip will have an exit code of 2 due to the "unsafe" 'Applications' symlink.
            # GitHub treats this as a failure so ignore non-zero exit codes here.
            7zz x *.dmg -otmp_x86 || true
            rm *.dmg
        else
            7zz x ../mac_x86.dmg -otmp_x86 || true
        fi

        if [ -d tmp_x86/OBS.app ]; then
            mv tmp_x86/OBS.app steam-macos/x86
        else
            mv tmp_x86/*/OBS.app steam-macos/x86
        fi
        echo "::endgroup::"

        echo "::group::Extract and prepare macOS (arm64)"
        mkdir -p steam-macos/arm64
        if [[ -f ../mac_arm64.dmg.zip ]]; then
            unzip ../mac_arm64.dmg.zip
            7zz x *.dmg -otmp_arm64 || true
            rm *.dmg
        else
            7zz x ../mac_arm64.dmg -otmp_arm64 || true
        fi

        if [ -d tmp_arm64/OBS.app ]; then
            mv tmp_arm64/OBS.app steam-macos/arm64
        else
            mv tmp_arm64/*/OBS.app steam-macos/arm64
        fi

        cp ../source/CI/steam/scripts_macos/launch.sh steam-macos/launch.sh
        echo "::endgroup::"

    - name: Setup steamcmd
      if: steps.should-run.outputs.result == 'true'
      uses: CyberAndrii/setup-steamcmd@e19cd1516315ce46dbfffa47193f92fe42d1419e

    - name: Generate Steam auth code
      if: steps.should-run.outputs.result == 'true'
      id: steam-totp
      uses: CyberAndrii/steam-totp@0fc9e59dc5bbf4368d23d5a33956f104248da31a
      with:
        shared_secret: ${{ secrets.STEAM_SHARED_SECRET }}

    - name: Upload to Steam
      if: steps.should-run.outputs.result == 'true'
      run: |
        cd steam
        echo "::group::Prepare Steam build script"
        # The description in Steamworks for the build will be "github_<branch>-<tag/short hash>", e.g. "github_nightly-gaa73de952"
        sed 's/@@DESC@@/${{ steps.build-info.outputs.branch }}-${{ steps.build-info.outputs.desc }}/;s/@@BRANCH@@/${{ steps.build-info.outputs.branch }}/' ../source/CI/steam/obs_build.vdf > build.vdf
        echo "Generated file:"
        cat build.vdf
        echo "::endgroup::"
        echo "::group::Upload to Steam"
        steamcmd +login '${{ secrets.STEAM_USER }}' '${{ secrets.STEAM_PASSWORD }}' '${{ steps.steam-totp.outputs.code }}' +run_app_build "$(pwd)/build.vdf" +quit
        echo "::endgroup::"

    - name: Generate Steam auth code (Playtest)
      if: steps.should-run.outputs.result_playtest == 'true'
      id: steam-totp-playtest
      uses: CyberAndrii/steam-totp@0fc9e59dc5bbf4368d23d5a33956f104248da31a
      with:
        shared_secret: ${{ secrets.STEAM_SHARED_SECRET }}

    - name: Upload to Steam (Playtest)
      if: steps.should-run.outputs.result_playtest == 'true'
      run: |
        cd steam
        echo "::group::Prepare Steam build script"
        sed 's/@@DESC@@/${{ steps.build-info.outputs.branch }}-${{ steps.build-info.outputs.desc }}/;s/@@BRANCH@@/${{ env.STEAM_PLAYTEST_BRANCH }}/' ../source/CI/steam/obs_playtest_build.vdf > build_playtest.vdf
        echo "Generated file:"
        cat build_playtest.vdf
        echo "::endgroup::"
        echo "::group::Upload to Steam"
        steamcmd +login '${{ secrets.STEAM_USER }}' '${{ secrets.STEAM_PASSWORD }}' '${{ steps.steam-totp-playtest.outputs.code }}' +run_app_build "$(pwd)/build_playtest.vdf" +quit
        echo "::endgroup::"

    - name: Upload Steam build logs
      if: steps.should-run.outputs.result == 'true'
      uses: actions/upload-artifact@v3
      with:
        name: steam-build-logs
        path: ${{ github.workspace }}/steam/build/*.log
