#!/data/data/com.bai.diple.ide/files/usr/bin/sh
# shellcheck shell=dash

set -eu

is_executable_file() {
	test -f "$1" -a -x "$1"
}

show_usage() {
	echo "usage: chsh [-s shell]"
	echo "Change the login shell."
	echo
	if [ "${1:-}" = "login" ]; then
		echo "The shell value must be one of following and cannot be 'login':"
	else
		echo "The shell value must be one of following:"
	fi
	echo " - Empty value to restore default shell."
	echo " - Absolute path to shell starting with a '/'."
	echo " - Relative path to shell not starting with a '/' relative to '/data/data/com.bai.diple.ide/files/usr/bin'."
}

set_shell() {
	if [ -z "${1:-}" ]; then
		echo "Restoring default shell"
		rm -f "$HOME/.termux/shell"
		exit 0
	fi

	if [ "$1" = "login" ]; then
		show_usage "login"
		exit 1
	fi
	mkdir -p "$HOME/.termux"

	unset NEW_SHELL
	case "$1" in
		"/"*) NEW_SHELL="$1" ;;
		*) NEW_SHELL="/data/data/com.bai.diple.ide/files/usr/bin/$1" ;;
	esac

	SHELL_TARGET="$(realpath -s "$NEW_SHELL")"

	if ! is_executable_file "$SHELL_TARGET"; then
		echo "The shell file '$SHELL_TARGET' is not an executable file." 1>&2
		exit 1
	fi

	if [ "$SHELL_TARGET" -ef "/data/data/com.bai.diple.ide/files/usr/bin/login" ]; then
		echo "The shell file '$SHELL_TARGET' must not point to the '/data/data/com.bai.diple.ide/files/usr/bin/login' script." 1>&2
		exit 1
	fi

	ln -sf "$SHELL_TARGET" "$HOME/.termux/shell"
}

O=`getopt -l help -- hs: "$@"`
eval set -- "$O"
while true; do
	case "$1" in
		-h|--help) show_usage; exit 0;;
		-s) set_shell "$2"; exit 0;;
		--)	shift; break;;
		*)	echo Error; show_usage; exit 1;;
	esac
done

DEFAULT_SHELL=bash
if ! is_executable_file "/data/data/com.bai.diple.ide/files/usr/bin/$DEFAULT_SHELL"; then DEFAULT_SHELL=sh; fi

echo Changing the login shell
echo Enter the new value, or press ENTER for the default
printf "        Login Shell [$DEFAULT_SHELL]: "
read shell

set_shell "$shell"
