#!/usr/bin/env bash
# Author: Mikhail Tergoev (linux-gaming.ru)
# License MIT
########################################################################
unset PW_AUTOPLAY PW_SET_LANG PW_SILENT_INSTALL
export portname="PortProton"
export port_ver=1.5
########################################################################
cd "$(dirname "$(readlink -f "$0")")"
script_path="$(pwd)"
def_path="${HOME}/${portname}"
########################################################################
fatal () {
	echo -e "\n${1}\n"
	exit 1
}
########################################################################
if [ "$(id -u)" == "0" ] ; then
	$yad_gui --error --text "\nDo not run ${portname} from the superuser!" 2>/dev/null
	fatal "Do not run the script from the superuser!"
fi
########################################################################
[ -z "${XDG_DATA_HOME}" ] && export XDG_DATA_HOME="$HOME/.local/share"
PP_CONFIG_FILE="${HOME}/.config/${portname}.conf"
if [ -f "${XDG_DATA_HOME}/PortWINE/PortProton/data/scripts/start.sh" ] ; then
	echo "${XDG_DATA_HOME}/PortWINE/PortProton" > "${PP_CONFIG_FILE}"
elif [ -f "${HOME}/PortWINE/PortProton/data/scripts/start.sh" ] ; then
	echo "${XDG_DATA_HOME}/PortWINE/PortProton" > "${PP_CONFIG_FILE}"
fi

if [ "$script_path" == "/usr/bin" ] && [ -f "${PP_CONFIG_FILE}" ] ; then
	export PORT_WINE_PATH="$(cat "${PP_CONFIG_FILE}" | head -n 1)"
	if [ -f "${PORT_WINE_PATH}/data/scripts/start.sh" ] ; then
		echo "${port_ver}" > "${PORT_WINE_PATH}/data/tmp/${portname}_ver"
		/usr/bin/env bash "${PORT_WINE_PATH}/data/scripts/start.sh" "$@"
		exit 0
	else
		rm -f "${PP_CONFIG_FILE}"
	fi
fi
if [[ "${LANG}" == "ru_RU.UTF-8" ]]
then PW_SET_LANG="Russian"
else PW_SET_LANG="English"
fi
########################################################################
pw_notify_send () {
	if command -v notify-send &>/dev/null ; then
		if [[ -f "/usr/share/icons/hicolor/scalable/apps/portproton.svg" ]]
		then notify-send -u normal -a PortProton -i "/usr/share/icons/hicolor/scalable/apps/portproton.svg" $@ "${PW_NOTIFY_TEXT}"
		else notify-send -u normal -a PortProton $@ "${PW_NOTIFY_TEXT}"
		fi
	fi
}
########################################################################
unset PW_USE_NS
YAD_PORTABLE_VER="12_3"
if command -v yad &>/dev/null ; then
	yad_gui="yad --window-icon=portproton.svg --borders=10 --center --text-align=center"
elif curl -f -# -A "Mozilla/5.0 (compatible; Konqueror/2.1.1; X11)" \
	-H 'Cache-Control: no-cache, no-store' -H 'Pragma: no-cache' \
	-L "https://github.com/Castro-Fidel/PortWINE/releases/download/yad_portable_v${YAD_PORTABLE_VER}/yad_portable_v${YAD_PORTABLE_VER}.tar.xz" \
	-o "${HOME}/yad_portable_v${YAD_PORTABLE_VER}.tar.xz"
then
	mkdir -p "${HOME}/.local/bin/" &>/dev/null
	tar -Jxhvf "${HOME}/yad_portable_v${YAD_PORTABLE_VER}.tar.xz" -C "${HOME}/.local/bin/"
	if [[ -f "${HOME}/.local/bin/yad_portable_v${YAD_PORTABLE_VER}" ]]
	then yad_gui="${HOME}/.local/bin/yad_portable_v${YAD_PORTABLE_VER} --borders=10 --center --text-align=center"
	else PW_USE_NS=1
	fi
else
	PW_USE_NS=1
fi
########################################################################
export PW_SILENT_INSTALL=1
export PW_AUTOPLAY=1
export INSTALLING_PORT=1
########################################################################
if [[ "${PW_USE_NS}" != "1" ]] ; then
	case $PW_SET_LANG in
		"Russian")
			inst1=$($yad_gui --title  "Install ${portname}" --text "Выберите путь для установки (обновления) ${portname},\nили оставьте его по умолчанию.\n\nВнимание:\nУстанавливать необходимо на файловую систему Linux (ext4, btrfs и прочие)." --list --radiolist --width=600 --height=200 \
			--column="Выбор" --column "Путь:" \
			TRUE "${def_path}" \
			FALSE "Другой путь...")
			[ "$?" != "0" ] && exit 1
			inst1="$(echo $inst1 | awk -F'|' '{print $2}')"
			case $inst1 in
				"${def_path}")
					D_PATH="${def_path}" ;;
				"Другой путь...")
					D_PATH="$($yad_gui --file --directory --title="Выберите путь..." --width=800 --height=800)" ;;
			esac ;;
		"English")
			inst1=$($yad_gui --title  "Install ${portname}" --text "Select the installation path (update) port,\nor leave it in default." --list --radiolist --width=600 --height=200 \
			--column="Set..." --column "Path:" \
			TRUE "${def_path}" \
			FALSE "Other path...")
			inst1="$(echo $inst1 | awk -F'|' '{print $2}')"
			[ "$?" != "0" ] && exit 1
			case $inst1 in
				"${def_path}")
					D_PATH="${def_path}" ;;
				"Other path...")
					D_PATH="$($yad_gui --file --directory --title="Select the path...")" ;;
			esac ;;
	esac
	[[ -z "${D_PATH}" ]] && fatal
	echo "${D_PATH}" | grep -i "${portname}" 2>/dev/null || D_PATH="${D_PATH}/${portname}"

	case $PW_SET_LANG in
		"Russian")
			progress_bar() {
			$yad_gui --progress --title="Установка..." --text="Настройка ${portname}" --pulsate --auto-close --auto-kill --width=500
			} ;;
		"English")
			progress_bar() {
			$yad_gui --progress --title="Install..." --text="Install ${portname}" --pulsate --auto-close --auto-kill --width=500
			} ;;
	esac
else
	D_PATH="${def_path}"
	PW_NOTIFY_TEXT="Installing PortProton..."
	pw_notify_send
fi
########################################################################
export PORT_WINE_PATH="${D_PATH}"
echo "${PORT_WINE_PATH}" > "${PP_CONFIG_FILE}"
if [ ! -d "${PORT_WINE_PATH}" ] ; then
    mkdir -p "$PORT_WINE_PATH" || fatal "Cannot create a directory: $PORT_WINE_PATH"
else
	rm -fr "${PORT_WINE_PATH}/data/tmp"
	rm -f "${PORT_WINE_PATH}/data/scripts/"* 2>/dev/null
fi
########################################################################
mkdir -p "${PORT_WINE_PATH}/data/tmp"
echo "${port_ver}" > "${PORT_WINE_PATH}/data/tmp/${portname}_ver"
case "${PW_SET_LANG}" in
	"Russian") echo "RUS" > "${PORT_WINE_PATH}/data/tmp/${portname}_loc" ;;
	"English") echo "ENG" > "${PORT_WINE_PATH}/data/tmp/${portname}_loc" ;;
esac
########################################################################
if [[ "${PW_USE_NS}" != "1" ]] ; then
	PW_NOTIFY_TEXT="Installing PortProton..."
	pw_notify_send
fi
export PORT_WINE_TMP_PATH="${PORT_WINE_PATH}/data/tmp"
cd "${PORT_WINE_PATH}"
echo -e "\nTry download scripts from gitlab.eterfund.ru..."
if ! curl -f -# -A "Mozilla/5.0 (compatible; Konqueror/2.1.1; X11)" -H 'Cache-Control: no-cache, no-store' -H 'Pragma: no-cache' \
	-L "https://gitlab.eterfund.ru/Castro-Fidel/PortWINE/-/archive/master/PortWINE-master.tar.gz" \
	-o "${PORT_WINE_TMP_PATH}/PortWINE-master.tar.gz"
then
	echo -e "\nError.\nTry download scripts from github.com..."
	curl -f -# -A "Mozilla/5.0 (compatible; Konqueror/2.1.1; X11)" -H 'Cache-Control: no-cache, no-store' -H 'Pragma: no-cache' \
	-L "https://github.com/Castro-Fidel/PortWINE/archive/refs/heads/master.tar.gz" \
	-o "${PORT_WINE_TMP_PATH}/PortWINE-master.tar.gz"
	[ "$?" != "0" ] && fatal "Critical error during file download!"
fi
echo "Try unpacking scripts..."
tar -xvzf "${PORT_WINE_TMP_PATH}/PortWINE-master.tar.gz" -C "${PORT_WINE_TMP_PATH}"
if [ "$?" = "0" ] ; then
	[ ! -d "${PORT_WINE_PATH}/data/" ] && mkdir "${PORT_WINE_PATH}/data/"
	cp -fr "${PORT_WINE_TMP_PATH}/PortWINE-master/data_from_portwine/"* "${PORT_WINE_PATH}/data/"
	rm -f "${PORT_WINE_TMP_PATH}/PortWINE-master.tar.gz"
	rm -fr "${PORT_WINE_TMP_PATH}/PortWINE-master/"
	export scripts_current_ver=$(cat "${PORT_WINE_PATH}/data/scripts/var" | grep SCRIPTS_NEXT_VERSION | awk -F "=" '{print $2}')
	echo "${scripts_current_ver}" > "${PORT_WINE_TMP_PATH}/scripts_ver"
else
	rm -f "${PORT_WINE_TMP_PATH}/PortWINE-master.tar.gz"
	[ "$?" != "0" ] && fatal "Critical error during file unpacking!"
fi
########################################################################
cd "${PORT_WINE_PATH}/data/scripts"
/usr/bin/env bash "${PORT_WINE_PATH}/data/scripts/setup.sh" && exit 0
