#!/bin/sh

# Copyright (C) 2022 Dyne.org Foundation
##
# This source code is free software; you can redistribute it and/or
# modify it under the terms of the GNU Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This source code is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.	Please refer
# to the GNU Public License for more details.
#
# You should have received a copy of the GNU Public License along with
# this source code; if not, , see <https://www.gnu.org/licenses/>.

mkdir -p "$HOME/bin"

# WSL specific: build and update an executable path to win (.exe)
# applications linked in the startupmenu directory
function wrap_exe() {
	if [ -r "$1" ]; then
		cat <<EOF > "$2"
#!/bin/sh
# this wrapper was generated by .dotfiles/system/startmenu
# on: `date`
arg="\$1"
if [ -r "\$1" ]; then # argument is a file
   arg=\`wslpath -w "\$1"\`
fi
"$1" "\$arg"
EOF
		chmod +x "$2"
	fi
}

function populate_startmenu() {
	local oldhash='new'
	if [ -r ~/.startmenu_hash ]; then
		oldhash=`cat ~/.startmenu_hash`; fi
	local newhash=`echo ${lnks} | sha1sum -z | cut -d' ' -f 1`
	if [ "$oldhash" != "new" ]; then
		if [ "$oldhash" == "$newhash" ]; then return; fi
	fi
	echo "Populating startmenu links..."
	if ! [ -d ${HOME}/bin ]; then
		mkdir ${HOME}/bin
		prepend-path ${HOME}/bin
	fi
	local tmp=`mktemp`
	while IFS= read -r line; do
		eval `lnkinfo "$line" | awk -F":" '
/Local path/ {  printf "path=\"C:%s\"", $3 }
'`
		echo `wslpath "$path"` >> $tmp
	done <<< ${lnks}
	local lnks=`sort $tmp | grep -i 'EXE$' | uniq | grep -iv setup | grep -iv update | grep -iv install `
	rm -f $tmp
	while IFS= read -r line; do
		local exe=`basename "$line" | tr [:upper:] [:lower:]`
		# echo " $exe -> $line"
		# ln -sf "$line" "${HOME}/bin/$exe"
		wrap_exe "$line" "${HOME}/bin/$exe"
	done <<< ${lnks}
	echo ${newhash} > ~/.startmenu_hash
}

if [ -d "/mnt/c/ProgramData/Microsoft/Windows/Start Menu/Programs" ]; then

	if ! [ -d ${HOME}/StartMenu ]; then
		ln -sf "/mnt/c/ProgramData/Microsoft/Windows/Start Menu/Programs" \
		   "${HOME}/StartMenu"
	fi

	if command -v lnkinfo > /dev/null; then
		lnks=`find ~/StartMenu/ -maxdepth 2 -name '*.lnk'`
		populate_startmenu ${lnks}
	fi
fi

# handy aliases
if [ -r "${HOME}/bin/msedge.exe" ]; then alias edge='msedge.exe'; fi
if [ -r "${HOME}/bin/winword.exe" ]; then alias word='winword.exe'; fi

# hardcode some
wrap_exe /mnt/c/Windows/System32/notepad.exe ${HOME}/bin/notepad.exe
wrap_exe /mnt/c/Windows/System32/calc.exe ${HOME}/bin/calculator.exe
