#!/usr/bin/env sh

# ~/.local/bin/chromium
# chromium plaintext configuration overlay script
# mangles configuration during pre-run

# useragent string
# fake being MS edge on windows to avoid cloudflare serving webp/avif images
UA_STRING="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 \
(KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36 Edg/126.0.2592.102"

# allow multiple chromium profiles to co-exist by deriving profile name from
# script name, eg. this script being renamed or symlinked as 'chrome-temp' will
# use profile located at '~/.config/chrome-temp'
CONF="$HOME/.config/${0##*/}"

# redirect cache writes to ramdisk defined by pam_systemd
CACHE="$XDG_CACHE_HOME/${0##*/}"

# DO NOT mangle config if chromium is already running
if ! ps -e | fgrep -q 'chromium'; then
	# on first-run, regenerate chromium config
	if [ ! -d "$CONF/Default" ]; then

		# dumb hack to checkout persistent settings if not found
		mkdir -p "$CONF"
		git meta list-files | fgrep '.config/chromium' \
			| xargs -I'{}' git meta --work-tree="$CONF" checkout "{}"
		cd "$CONF/.config/chromium" && mv * ../.. && rm -rf '.config/chromium'

		# warn user of first run
		# allow first run to generate default preferences
		# automatically enable use of theme colors
		cat <<- EOF | /usr/bin/chromium "data:text/html;base64,$(base64 -w 0)" \
			--install-autogenerated-theme='0,0,0' -incognito &
			<style>
				html { color: #FFFFFF; background: #222222; }
				.note { text-align: center; }
			</style>
			<div class="note">
				<h1>Regenerating <code>chromium</code>
					preferences on first run...</h1>
				<p>This only needs to be done once.</p>
				<p><b>DO NOT</b> interact with this window,
					<code>chromium</code> will restart momentarily.</p>
			</div>
		EOF
		# wait until chromium spins up 12 processes before SIGTERM
		while [ $(ps -e | fgrep -c 'chromium') -lt 12 ]; do :; done
		kill "$!"
	fi

	# inject persistent SQL omnibox settings
	[ -f "$CONF/omnibox.sql" ] && {
		sqlite3 -cmd '.timeout 1000' \
			"$CONF/Default/Web Data" < "$CONF/omnibox.sql"
	}

	# inject persistent JSON preferences and chromium flags
	for f in 'Default/Preferences' 'Local State'; do
		mine="$(echo "${f#*/}" | tr ' A-Z' '_a-z').conf"
		[ -f "$CONF/$f" ] || continue
		[ -f "$CONF/$mine" ] || continue

		# pipe multiple jq filters together
		# remove trailing newline
		IFS='
		'
		unset json hex
		for g in $(cpp -P < "$CONF/$mine" 2> /dev/null); do
			json="${json}.$g|"
		done
		json="${json%|}"
		unset IFS

		# rewrite #RRGGBB hex colors to signed integer representing 0xBBGGRRAA
		# in two's complement hexadecimal with alpha channel always 0xFF
		for g in $(echo "$json" | egrep -o '\#[A-Fa-f0-9]{6}'); do
			for h in FF $(echo "$g" | tr -d '#' | sed -E 's/.{2}/& /g'); do
				hex="$h$hex"
			done
			int="$(echo "0x$hex" | xxd -r | od -A n -t dI | tr -d ' ')"
			json="$(echo "$json" | sed "s/$g/$int/g")"
		done

		jq -Mc "$json" < "$CONF/$f" > "$CONF/$f.1" && \
			mv "$CONF/$f.1" "$CONF/$f"
	done
fi

# 08/2024: disable UA spoofing because it triggers cloudflare filters on many sites
/usr/bin/chromium \
	--user-data-dir="$CONF" --disk-cache-dir="$CACHE" \
	"$@"
#	--user-agent="$UA_STRING" "$@"