Most of it is taken from this gist. I just tweaked the script to check the right theme at startup in case the theme change occured when iTerm2 was closed.
Make sure the theme is the same as the themes you have installed (Preferences > Profiles > Colors > Color Presets...). I personally use Solarized Dark and Solarized Light
From someone on the linked gist:
First-time installation steps for me:
- Download the script from GitHub by right-clicking on Raw button and save as...
- copy the script to
$HOME/Library/Application Support/iTerm2/Scripts/AutoLaunch
- create AutoLaunch folder if it does not exist
- go to iTerm2 > Scripts > AutoLaunch
- You will be prompted to download the Python runtime, do it.
- Switch the dark/light mode in macOS, iTerm2 should change color if your script does not work after you restart iTerm2, make sure that Preferences -> Magic -> Enable Python API is checked and this setting is saved