#!/bin/bash
# wslu - Windows 10 linux Subsystem Utility
# Component of Windows 10 linux Subsystem Utility
# <https://github.com/wslutilities/wslu>
# Copyright (C) 2019 Patrick Wu
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program 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.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

# Version
wslu_version=3.0.0-0

# Speed up script by not using unicode.
LC_ALL=C
LANG=C

# prevent bash -x
set +x

# when --verbose, verbose; when --debug, debug.
#
# They should not exist at the same time, otherwise
# the output would be too messy.
wslu_debug=0
if [ "$1" == "--verbose" ]; then
	echo -e '\e[38;5;202m\033[1m[verbose] Showing verbose output. \033(B\033[m'
	shift
	set -x
elif [ "$1" == "--debug" ]; then
	wslu_debug=1
	echo -e '\e[38;5;202m\033[1m[debug] Showing debug output. \033(B\033[m'
	shift
fi

# checking interoperability
grep enabled /proc/sys/fs/binfmt_misc/WSLInterop >/dev/null || (echo -e "\e[31m\033[1m[error] WSL Interoperability is disabled. Please enable it before using WSL.\033(B\033[m"; exit 1)

# variables
## color
black=$(echo -e '\e[30m')
red=$(echo -e '\e[31m')
green=$(echo -e '\e[32m')
brown=$(echo -e '\e[33m')
blue=$(echo -e '\e[34m')
purple=$(echo -e '\e[35m')
cyan=$(echo -e '\e[36m')
yellow=$(echo -e '\e[1;33m')
white=$(echo -e '\e[1;37m')
dark_gray=$(echo -e '\e[1;30m')
light_red=$(echo -e '\e[1;31m')
light_green=$(echo -e '\e[1;32m')
light_blue=$(echo -e '\e[1;34m')
light_purple=$(echo -e '\e[1;35m')
light_cyan=$(echo -e '\e[1;36m')
light_gray=$(echo -e '\e[37m')
orange=$(echo -e '\e[38;5;202m')
light_orange=$(echo -e '\e[38;5;214m')
bold=$(echo -e '\033[1m')
reset=$(echo -e '\033(B\033[m')

## indicator
info="${green}[info]${reset}"
input_info="${cyan}[input]${reset}"
error="${red}[error]${reset}"
warn="${orange}[warn]${reset}"

## Windows build number constant
readonly BN_SPR_CREATORS=15063		#1703, Redstone 2, Creators Update
readonly BN_FAL_CREATORS=16299		#1709, Redstone 3, Fall Creators Update
readonly BN_APR_EIGHTEEN=17134		#1803, Redstone 4, April 2018 Update
readonly BN_OCT_EIGHTEEN=17763		#1809, Redstone 5, October 2018 Update
readonly BN_MAY_NINETEEN=18362		#1903, 19H1, May 2019 Update
readonly BN_NOV_NINETEEN=18363		#1909, 19H2, November 2019 Update

# functions
function debug_echo {
	[ $wslu_debug -eq 1 ] && echo "${orange}${bold}[debug]${reset} $@"
}

function help {
	app_name=$(basename "$1")
	echo -e "$app_name - Part of wslu, a collection of utilities for Windows 10 Windows Subsystem for Linux
Usage: $2

For more help for $app_name, please use `man $app_name` visit the following site: https://wslu.patrickwu.space/man/$app_name.html"
}

function double_dash_p {
	echo "${@//\\/\\\\}"
}

function interop_prefix {

	win_location="/mnt/"
	if [ -f /etc/wsl.conf ]; then
		tmp="$(awk -F '=' '/root/ {print $2}' /etc/wsl.conf | awk '{$1=$1;print}')"
		[ "$tmp" == "" ] || win_location="$tmp"
		unset tmp
	fi
	echo "$win_location"

	unset win_location
}

function sysdrive_prefix {
	win_location="$(interop_prefix)"
	hard_reset=0
	for pt in $(ls "$win_location"); do
		if [ $(echo "$pt" | wc -l) -eq 1 ]; then
			if [ -d "$win_location$pt/Windows/System32" ]; then
				hard_reset=1
				win_location="$pt"
				break
			fi
		fi 
	done

	if [ $hard_reset -eq 0 ]; then
		win_location="c"
	fi

	echo "$win_location"

	unset win_location
	unset hard_reset
}

function chcp_com {
	"$(interop_prefix)$(sysdrive_prefix)"/Windows/System32/chcp.com "$@" >/dev/null
}

function winps_exec {
	chcp_com "$(cat ~/.config/wslu/oemcp)"
	"$(interop_prefix)$(sysdrive_prefix)"/Windows/System32/WindowsPowerShell/v1.0/powershell.exe -NoProfile -NonInteractive –ExecutionPolicy Bypass -Command "$@"
	EXIT_STATUS=$?
	chcp_com 65001
	return $EXIT_STATUS
}

function baseexec_gen {
	wslutmpbuild=$("$(interop_prefix)$(sysdrive_prefix)"/Windows/System32/reg.exe query "HKLM\\Software\\Microsoft\\Windows NT\\CurrentVersion" /v CurrentBuild | tail -n 2 | head -n 1 | sed -e 's|\r||g')
	wslutmpbuild=${wslutmpbuild##* }
	wslutmpbuild="$(( $wslutmpbuild + 0 ))"
	if [ $wslutmpbuild -ge $BN_MAY_NINETEEN ]; then
		# The environment variable only available in 19H1 or later.
		wslu_distro_regpath=$("$(interop_prefix)$(sysdrive_prefix)"/Windows/System32/reg.exe query "HKCU\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Lxss" /s /f DistributionName 2>&1 | grep -B1 -e "$WSL_DISTRO_NAME" | head -n1 | sed -e 's|\r||g')
		if "$(interop_prefix)$(sysdrive_prefix)"/Windows/System32/reg.exe query "$wslu_distro_regpath" /v PackageFamilyName &>/dev/null; then
			# if it is a store distro
			wslu_distro_packagename=$("$(interop_prefix)$(sysdrive_prefix)"/Windows/System32/reg.exe query "$wslu_distro_regpath" /v PackageFamilyName | tail -n 2 | head -n 1 | sed -e 's|\r||g')
			wslu_distro_packagename=${wslu_distro_packagename##* }
			wslu_base_exec_folder_path="$(wslpath "$(double_dash_p $(winps_exec "Write-Output \$Env:LOCALAPPDATA" | tr -d "\r"))\\Microsoft\\WindowsApps\\$wslu_distro_packagename")"
			wslpath -w "$(find "$wslu_base_exec_folder_path" -name "*.exe")" > ~/.config/wslu/baseexec
		else
			# if it is imported distro
			echo "$(double_dash_p "$(wslpath -w "$(interop_prefix)$(sysdrive_prefix)")")\\Windows\\System32\\wsl.exe -d $WSL_DISTRO_NAME" > ~/.config/wslu/baseexec
		fi
	else
		# older version fallback.
		echo "$(double_dash_p "$(wslpath -w "$(interop_prefix)$(sysdrive_prefix)")")\\Windows\\System32\\wsl.exe" > ~/.config/wslu/baseexec
	fi
}

function wslu_file_check {
	if [[ ! -f "$1/$2" ]]; then
		echo "${warn} $2 not found in Windows directory. Copying right now..."
		[[ -d "$1" ]] || mkdir "$1"
		if [[ -f "/usr/share/wslu/$2" ]]; then
			cp "/usr/share/wslu/$2" "$1"
			echo "${info} $2 copied. Located at \"$1\"."
		else
			echo "${error} $2 not found. Failed to copy."
			exit 30
		fi
	fi
}


# first run, saving some information
if [ ! -d ~/.config/wslu ]; then
	mkdir -p ~/.config/wslu
fi

# generate oem codepage
if [ ! -f ~/.config/wslu/oemcp ]; then
	"$(interop_prefix)$(sysdrive_prefix)"/Windows/System32/reg.exe query "HKLM\\SYSTEM\\CurrentControlSet\\Control\\Nls\\CodePage" /v OEMCP 2>&1 | sed -n 3p | sed -e 's|\r||g' | grep -o '[[:digit:]]*' > ~/.config/wslu/oemcp
fi

# generate base exe locaiton
if [ ! -f ~/.config/wslu/baseexec ]; then
	# if it is not generated
	baseexec_gen
elif grep -q "/" ~/.config/wslu/baseexec; then
	# if baseexec is using the old linux style, regenerate
	baseexec_gen
elif which "$(cat ~/.config/wslu/baseexec)" &>/dev/null; then
	# if baseexec cannnot be executed, regenerate
	baseexec_gen
fi

# basic distro detection
distro="$(head -n1 /etc/os-release | sed -e 's/NAME=\"//g')"
case $distro in
	*Pengwin*) distro="pengwin";;
	*WLinux*) distro="wlinux";;
	Ubuntu*) distro="ubuntu";;
	*Debian*) distro="debian";;
	*Kali*) distro="kali";;
	openSUSE*) distro="opensuse";;
	SLES*) distro="sles";;
	Alpine*) distro="alpine";;
	Arch*) distro="archlinux";;
	*Oracle*) distro="oracle";;
	Scientific*) distro="scilinux";;
	*Fedora*) distro="fedora";;
	*Generic*) [ "fedora" == "$(grep -e "LIKE=" /etc/os-release | sed -e 's/ID_LIKE=//g')" ] && distro="oldfedora" || distro="unknown";;
	*) distro="unknown";;
esac
\n
# shellcheck shell=bash
version="01"

help_short="wslgsu [-u USERNAME] [-n NAME] [-S] SERVICE/COMMAND\nwslgsu [-hv]"

isService=0
wa_gs_commd=""
wa_gs_name=""
wa_gs_user="root"

while [ "$1" != "" ]; do
	case "$1" in
		-u|--user) shift; wa_gs_user="$1"; shift;;
		-n|--name) shift; wa_gs_name="$1"; shift;;
		-S|--service) isService=1; shift;;
		-h|--help) help "wslact" "$help_short"; exit;;
		*) wa_gs_commd="$*";break;;
	esac
done

if [[ "$wa_gs_commd" != "" ]]; then
	tmp_location="$(wslvar -s TMP)"
	up_location=""
	tpath="$(double_dash_p "$tmp_location")" # Windows Temp, Win Double Sty.
	tpath_linux="$(wslpath "$tmp_location")" # Windows Temp, Linux WSL Sty.
	script_location_win="$(wslvar -s USERPROFILE)\\wslu" #  Windows wslu, Win Double Sty.
	script_location="$(wslpath "$script_location_win")" # Windows wslu, Linux WSL Sty.

	# Check presence of sudo.ps1 and 
	wslu_file_check "$script_location" "sudo.ps1"
	wslu_file_check "$script_location" "runHidden.vbs"

	# check if it is a service or a command
	if [[ $isService -eq 1 ]]; then
	# service
		# handling no name given case
		if [[ "$wa_gs_name" = "" ]]; then
			wa_gs_name="$wa_gs_commd"
		fi
		wa_gs_commd="wsl.exe -d $WSL_DISTRO_NAME -u $wa_gs_user service $wa_gs_commd start"
	else
	# command
		# handling no name given case
		if [[ "$wa_gs_name" = "" ]]; then
			wa_gs_name=$(basename "$(echo "$wa_gs_commd" | awk '{print $1}')")
		fi
		wa_gs_commd="wsl.exe -d $WSL_DISTRO_NAME -u $wa_gs_user $wa_gs_commd"
	fi

	# shellcheck disable=SC2028
	tee "$tpath_linux"/tmp.ps1 << EOF
Import-Module 'C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\Modules\\Microsoft.PowerShell.Utility\\Microsoft.PowerShell.Utility.psd1';\$action = New-ScheduledTaskAction -Execute 'C:\\Windows\\System32\\wscript.exe'  -Argument '$script_location_win\\runHidden.vbs $wa_gs_commd';
\$trigger =  New-ScheduledTaskTrigger -AtLogOn -User \$env:userdomain\\\$env:username; \$task = New-ScheduledTask -Action \$action -Trigger \$trigger -Description \"Start service $wa_gs_name from $WSL_DISTRO_NAME when computer start up; Generated By WSL Utilities\";
Register-ScheduledTask -InputObject \$task -TaskPath '\\' -TaskName 'WSLUtilities_Actions_Startup_$wa_gs_name';
EOF
	echo "${warn} WSL Utilities is adding \"${wa_gs_name}\" to Task Scheduler; A UAC Prompt will show up later. Allow it if you know what you are doing."
	if winps_exec "$script_location_win"\\sudo.ps1 "$tpath"\\tmp.ps1; then
		rm -rf "$tpath_linux/tmp.ps1"
		echo "${info} Startup \"${wa_gs_name}\" added."

	else
		rm -rf "$tpath_linux/tmp.ps1"
		echo "${error} Adding Startup \"${wa_gs_name}\" failed."
		exit 1
	fi
else
	echo "${error} No input, aborting"
	exit 21
fi

unset isService
unset wa_gs_commd
unset wa_gs_name
unset wa_gs_user
