#!/bin/bash
# Marks Steam's shared redistributables as already run in every Proton prefix, and in the
# template Proton makes new prefixes from.
#
# A game whose depot lists _CommonRedist makes the client run the real installer inside the
# prefix on first launch. Those are x86 bundles, so they run under FEX, and the 2019 one leaves
# a task behind every time: its main thread exits while a helper stays blocked reading a pipe it
# also holds the write end of, so the process never reaps and the client keeps waiting on it.
#
# The client skips a "Run Process" block whose HasRunKey is already set, which is the same escape
# WineUtils.seedVcRedistRegistryIfDllsPresent() takes for the app's own containers. The names and
# versions come out of the install scripts rather than a list kept here, because Valve revises
# them. Only the values a registry file does not already hold are added, so a file that is
# already covered is not written at all.
#
#   bannerlator-seed-redists STEAM_ROOT
#       Every template and prefix in both libraries. Run as the session starts.
#   bannerlator-seed-redists --launch TOOL_DIR
#       From the compatibility tool, before it hands a launch to Proton: the template of the
#       Proton in TOOL_DIR and the prefix of the title being launched, plus whichever of that
#       title's own install-script steps are redistributables.
#
# Seeding at launch is what closes the race. The client creates a new prefix from the template and
# runs the title's install scripts in one go, so a template seeded on a timer was too late whenever
# the client had just installed or updated that Proton.
#
# Whether a file is covered is read from the file itself rather than from a stamp beside it. A
# stamp outlived the file it vouched for: the client replaces the template's system.reg when it
# updates Proton and leaves a file it did not ship where it is, and a running wineserver writes its
# own copy of a prefix's registry over values appended under it.
set -u

launch=
if [ "${1:-}" = --launch ]; then
  launch=1
  tool=${2:?tool dir}
  steam_root=${STEAM_COMPAT_CLIENT_INSTALL_PATH:-${XDG_DATA_HOME:-$HOME/.local/share}/Steam}
else
  steam_root=${1:?steam root}
fi
libraries=("$steam_root" /mnt/droiddeck-sd)

list=$(mktemp) || exit 0
trap 'rm -f "$list"' EXIT

# "key<TAB>name" for every process an install script would run: the HasRunKey the client sets once
# it has run it, and the name of its block, one level inside "Run Process". With only_redists set,
# a block counts only when it is one of the common redistributables: a title's own script can also
# hold its setup steps (a key, a launcher, a first-run tool), which have to run for real.
entries() {
  local only_redists=$1
  shift
  [ "$#" -gt 0 ] || return 0
  awk -v only="$only_redists" '
    function flush() {
      if (name == "" || key == "")
        return
      if (only && index(tolower(key), "\\\\commonredist\\\\") == 0 && !redist)
        return
      printf "%s\t%s\n", key, name
    }
    FNR == 1 { depth = 0; section = ""; name = ""; key = ""; redist = 0 }
    /^[[:space:]]*\{/ { depth++; next }
    /^[[:space:]]*\}/ {
      if (depth == 3) {
        if (tolower(section) == "run process")
          flush()
        name = ""; key = ""; redist = 0
      }
      depth--
      next
    }
    {
      n = split($0, part, "\"")
      if (n < 3)
        next
      if (depth == 1) { section = part[2]; next }
      if (depth == 2) { name = part[2]; key = ""; redist = 0; next }
      if (depth == 3 && n >= 5) {
        field = tolower(part[2])
        if (field == "hasrunkey")
          key = part[4]
        else if (field ~ /^process/ && tolower(part[4]) ~ /vcredist|vc_redist|vcrun|directx|dxsetup|dotnet|ndp[0-9]|netfx|xna|physx|openal|oalinst/)
          redist = 1
      }
    }
  ' "$@"
}

# The install scripts every library shares.
shared=()
for library in "${libraries[@]}"; do
  redist="$library/steamapps/common/Steamworks Shared/_CommonRedist"
  [ -d "$redist" ] || continue
  while IFS= read -r -d '' f; do shared+=("$f"); done \
    < <(find "$redist" -iname 'installscript*.vdf' -print0 2>/dev/null | sort -z)
done
entries 0 "${shared[@]}" >"$list"
# The client downloads the scripts with the first game that wants them, which is too late for that
# game; until then the set they held when this was written stands in. (WinNative's list.)
[ -s "$list" ] || sed 's/^\([^ ]*\) /HKEY_LOCAL_MACHINE\\\\Software\\\\Valve\\\\Steam\\\\Apps\\\\CommonRedist\\\\\1\t/' >"$list" <<'KNOWN'
DirectX\\Jun2010 dxsetup
.NET\\4.8 4.8
vcredist\\2008 x86 SP1
vcredist\\2008 x64 SP1
vcredist\\2010 x86
vcredist\\2010 x64
vcredist\\2013 x86 12.0.30501
vcredist\\2013 x64 12.0.30501
vcredist\\2015 x86 Update 3 14.0.24215.0
vcredist\\2015 x64 Update 3 14.0.24215.0
vcredist\\2017 x86 14.10.25008.0
vcredist\\2017 x64 14.10.25008.0
vcredist\\2019 x86 14.28.29334.0
vcredist\\2019 x64 14.28.29334.0
vcredist\\2022 x86 14.51.36247.0
vcredist\\2022 x64 14.51.36247.0
KNOWN

# A title's own scripts, at launch, where the client says which title it is. They go into the
# template as well: the title's prefix may not exist yet, and a key under another title's
# HasRunKey is never read by anything else.
if [ -n "$launch" ] && [ -d "${STEAM_COMPAT_INSTALL_PATH:-}" ]; then
  own=()
  while IFS= read -r -d '' f; do own+=("$f"); done \
    < <(find "$STEAM_COMPAT_INSTALL_PATH" -maxdepth 3 -iname 'installscript*.vdf' -print0 2>/dev/null | sort -z)
  entries 1 "${own[@]}" >>"$list"
fi

# Appends to a registry file whichever of the listed values it lacks. The client writes these
# from 32-bit steam.exe, so its own copy lands under Wow6432Node; both spellings are seeded
# because the reader picks by its own word size. Only HKEY_LOCAL_MACHINE keys live in system.reg.
seed() {
  local reg=$1 block dated
  [ -f "$reg" ] || return 0
  block=$(awk -F'\t' -v now="$(date +%s)" '
    function want(path, name,   id) {
      id = tolower(path) SUBSEP name
      if (id in queued)
        return
      queued[id] = 1
      order[++count] = path
      value[count] = name
    }
    FNR == NR {
      path = $1
      if (tolower(substr(path, 1, 20)) != "hkey_local_machine\\\\")
        next
      path = substr(path, 21)
      want(path, $2)
      if (tolower(substr(path, 1, 10)) == "software\\\\" && tolower(substr(path, 11, 13)) != "wow6432node\\\\")
        want(substr(path, 1, 10) "Wow6432Node\\\\" substr(path, 11), $2)
      next
    }
    /^\[/ {
      current = substr($0, 2)
      sub(/\][^]]*$/, "", current)
      current = tolower(current)
      next
    }
    /^"/ {
      v = $0
      sub(/^"/, "", v)
      sub(/"=.*$/, "", v)
      have[current SUBSEP v] = 1
    }
    END {
      for (i = 1; i <= count; i++)
        if (!((tolower(order[i]) SUBSEP value[i]) in have))
          printf "\n[%s] %d\n\"%s\"=dword:00000001\n", order[i], now, value[i]
    }
  ' "$list" "$reg")
  # The stamp an earlier seeder kept beside the file; nothing reads it now.
  rm -f "$(dirname "$reg")/.bannerlator-redists"
  [ -n "$block" ] || return 0
  # Its date is kept: Proton reads a changed one on a template as a new template and upgrades
  # every prefix made from the old. The client leaves some depot files read-only.
  dated=$(mktemp) || return 0
  touch -r "$reg" "$dated"
  [ -w "$reg" ] || chmod u+w "$reg" 2>/dev/null
  if printf '%s\n' "$block" >>"$reg"; then
    echo "== seeded redist markers into $reg"
  fi
  touch -r "$dated" "$reg"
  rm -f "$dated"
}

if [ -n "$launch" ]; then
  for reg in "$tool"/files/share/default_pfx*/system.reg; do
    seed "$reg"
  done
  [ -n "${STEAM_COMPAT_DATA_PATH:-}" ] && seed "$STEAM_COMPAT_DATA_PATH/pfx/system.reg"
  exit 0
fi

for library in "${libraries[@]}"; do
  for reg in "$library"/steamapps/common/Proton*/files/share/default_pfx*/system.reg \
             "$library"/steamapps/compatdata/*/pfx/system.reg; do
    seed "$reg"
  done
done
for reg in "$steam_root"/compatibilitytools.d/*/files/share/default_pfx*/system.reg; do
  seed "$reg"
done
