#!/bin/bash
 
set -e
 
APP_ID=${1}
STEAM_USER=$USER
STEAM_DIR="/home/${STEAM_USER}/.steam/steam/steamapps"
APP_DIR="${STEAM_DIR}/compatdata/${APP_ID}"
WIN_DIR="${APP_DIR}/pfx/drive_c/windows"
WIN_SYS32_DIR="${WIN_DIR}/system32"
WIN_SYS64_DIR="${WIN_DIR}/syswow64"
VC_REDIST_x64_CKSUM=5eea714e1f22f1875c1cb7b1738b0c0b1f02aec5ecb95f0fdb1c5171c6cd93a3
VC_REDIST_x86_CKSUM=fdd1e1f0dcae2d0aa0720895eff33b927d13076e64464bb7c7e5843b7667cd14

function list_apps() {
  echo "Provide a steam ID from below"
  for d in ${STEAM_DIR}/appmanifest*.acf; do
    id=$(sed -rn 's/\s+"appid"\s+"(.+)\"/\1/p' < $d)
    name=$(sed -rn 's/\s+"name"\s+"(.+)\"/\1/p' < $d)
    echo -e "$id\t\t$name"
  done
  echo
  echo
  echo example for \'$name\' would be $0 $appid 
  echo
}	


function check_deps() {
  which sha256sum > /dev/null || (echo "sha256sum is required (on Ubuntu you can install it with 'sudo apt-get install coreutils')" && exit 1)
  which curl > /dev/null || (echo "curl is required (on Ubuntu you can install it with 'sudo apt-get install curl')" && exit 1)
  which cabextract > /dev/null || (echo "cabextract is required (on Ubuntu you can install it with 'sudo apt-get install cabextract')" && exit 1)
  test -d ${APP_DIR} || ( echo "$APP_DIR does not exist; application is not supported or installed" && exit 1)
  test -d ${WIN_DIR} || ( echo "$WIN_DIR does not exist; application is not supported or installed" && exit 1)
}
 
function cleanup() {
  local arch=$1
 
  rm -f vc_redist.$arch.exe
  rm -rf 0 a{0..11} u{0..31}
}
 
function backup() {
  files="ucrtbase.dll concrt140.dll msvcp140.dll vcamp140.dll vccorlib140.dll vcomp140.dll vcruntime140.dll"
  for f in $files; do
    test -f $f || continue
    echo "Backing up $f => ${f}.bak"
    cp -n $f ${f}.bak 2> /dev/null || true
  done

}
 
function download_and_replace() {
  local arch=$1
  echo "Downloading vc_redist.$arch.exe" 
  curl -s -O https://download.microsoft.com/download/9/3/F/93FCF1E7-E6A4-478B-96E7-D4B285925B00/vc_redist.$arch.exe
  echo "Validating archive"
  csum="VC_REDIST_${arch}_CKSUM"
  rm -f tmp.sha256
  echo "${!csum}  vc_redist.$arch.exe" > tmp.sha256
  sha256sum -c tmp.sha256 || rm -f tmp.sha256
  echo "Extracting archive"
  cabextract -q vc_redist.$arch.exe 2>/dev/null
  cabextract -q a10 2>/dev/null
  echo "Extraction done"
}
 
function replace_dlls() {
  local dir=$1
  local arch=$2
 
  echo "Patching $dir with arch $2"
  pushd "${dir}" > /dev/null
 
  backup
  cleanup $arch
  download_and_replace $arch
  cleanup $arch
  popd > /dev/null

  echo "Patching complete!"
}
 
if [ -z "${APP_ID}" ]; then
  list_apps
  exit 1
fi 

check_deps
replace_dlls "${WIN_SYS32_DIR}" x64
replace_dlls "${WIN_SYS64_DIR}" x86
