#! /bin/sh

# Invoke mintty terminal with Windows look-and-feel (color settings)
# and optionally invoke mined in it
#	- if script name ends with "ed"

#############################################################################
# Select invocation mode
case "$0" in
*ed)	prog="-e mined";;
*)	prog=;;
esac

#############################################################################
# Acquire Windows system color and font size settings

# acquire Windows system color settings
color () {
	regtool -v get "/HKEY_CURRENT_USER/Control Panel/Colors/$1" 2> /dev/null ||
	reg query 'HKEY_CURRENT_USER\Control Panel\Colors' /v $1 |
	sed -e "s,.*	,," -e t -e d
}

rgb () {
	printf "#%02X%02X%02X" `color $1`
}

setcolors () {
	colors="-bg `rgb Window` -fg `rgb WindowText`"
}

mincolors () {
	echo ForegroundColour=`color WindowText | sed -e 's/ /,/g'`
	echo BackgroundColour=`color Window | sed -e 's/ /,/g'`
}

# acquire Windows font size settings
# Configured font size from the registry (e.g. "MenuHeight") 
# cannot be used as especially Lucida Console scales much larger 
# than other fonts and sizes are not comparable among different fonts.
# So use a fixed base size and scale it by configured screen resolution.
metrics () {
	regtool -v get "/HKEY_CURRENT_USER/Control Panel/Desktop/WindowMetrics/$1" 2> /dev/null ||
	printf "%d" `reg query 'HKEY_CURRENT_USER\Control Panel\Desktop\WindowMetrics' /v $1 |
			sed -e "s,.*	,," -e t -e d`
}

fontsize () {
#	expr 0 - `metrics MenuHeight` / 16
	expr 14 \* `metrics AppliedDPI` / 100
}

minfontsize () {
	echo FontHeight=`fontsize`
}

#############################################################################
# Start terminal with appropriate parameters

locale=`echo ${LC_ALL:-${LC_CTYPE:-${LANG:-C}}} | sed -e "s,\..*,,"`

confattr="Locale|Charset|UseSystemColours|BoldAsBright|Scrollbar|WindowShortcuts|ZoomShortcuts"
(mincolors
 #echo FontHeight=...
 echo Locale=$locale
 echo Charset=UTF-8
 echo UseSystemColours=1
 echo BoldAsBright=0
 echo Scrollbar=0
 echo WindowShortcuts=0
 echo ZoomShortcuts=0
 egrep -v -e "^($confattr)=" \
 	"$HOME/.minttyrc"
) > "$HOME/.minttyrc.win"
(mintty -c "$HOME/.minttyrc.win" $prog "$@"
 if false
 then	# grab configuration changes for parameters not set here
 	egrep -e "^($confattr)=" \
 		"$HOME/.minttyrc" > "$HOME/.minttyrc.new"
 	egrep -v -e "^($confattr)=" \
 		"$HOME/.minttyrc.win" >> "$HOME/.minttyrc.new"
 	/bin/mv "$HOME/.minttyrc.new" "$HOME/.minttyrc"
 fi
) &

#############################################################################
# End
