#!/bin/bash
# must be run from mod basedir to find wads
# requires ripent from MHLT
# requires patched bspguy from https://ahl.omgwallhack.org/pkg/tools/bspguy/

set -ex

IFS=$'\n'
find maps/ -iname '*.bsp' -not -iname 'ahl_snowmax.bsp' | while read -r map; do
  base="$( basename "$map" .bsp )"
  echo "$base"
  ripent -noinfo -export "$map"
  cp maps/"$base".ent maps/"$base".old.ent
  # maybe update this to look up paths from a vdf file
  bspguy remove_unused_wads "$map" -waddir ../valve/ -waddir ../cstrike/ -o maps/"$base".new.bsp
  ripent -noinfo -export maps/"$base".new.bsp

  # bspguy mangles entities in unpredictable ways, so pull out the "wad" changes specifically
  awk -v repl="$(grep -a -m1 '^"wad"' maps/"$base".new.ent | sed 's/\r$//')" '
    !done && /^"wad"/ {
        print repl
        done = 1
        next
    }
    { print }
    ' maps/"$base".ent > maps/"$base".ent.tmp
  mv maps/"$base".ent.tmp maps/"$base".ent
  ripent -noinfo -import "$map"
# validate with
#    find -iregex '\./maps/[a-z0-9_]*\.bsp' -not -iname 'ahl_snowmax.bsp' | while read -r i; do base="$(basename $i .bsp )"; diff -apuNw maps/"$base".old.ent maps/"$base".ent; done | less
  rm maps/"$base".new.bsp maps/"$base".old.ent maps/"$base".new.ent maps/"$base".ent
done

