#!/bin/bash

if [ ! $UID -eq 0 ]; then
	echo "permission denied. (root required)"
	#exit 1
elif [[ ! $(cat /etc/*release | grep Ubuntu) ]]; then
	echo "this script can runs only on Ubuntu."
	exit 1
elif [[ ! $(dpkg -l | grep plymouth) ]]; then
	echo "please install plymouth at first."
	echo "install plymouth now? (Ctrl-C to abort)"
	read
	apt install plymouth || \
	exit 1
fi

themesdir="/usr/share/plymouth/themes"

_u_initramfs () {
	echo -e "\nbuilding new initramfs..."
	update-initramfs -u >/dev/null
	echo -e "DONE!!"
}

if [[ $(update-alternatives --list default.plymouth) ]]; then

  ####    FOR TO USE ALTERNATIVES    ####

	# list of plymouth themes
	l_themes=$(update-alternatives --display default.plymouth | sed "1,4d" | awk '{print $1}' | awk -F '/' '{print $6 "/" $7}')
	# number of plymouth themes
	n_themes=$(update-alternatives --display default.plymouth | sed "1,4d" | wc -l)
	# current plymouth theme
	c_theme=$(update-alternatives --display default.plymouth | sed -n "3p" | awk '{print $5}' | awk -F '/' '{print $6 "/" $7}')

	if [[ $(dpkg -l | grep galternatives) ]]; then
		echo "galternatives is installed."
		galternatives default.plymouth
	else
		for ((;;)) {
			echo -e "\nCURRENTLY SELECTED :"
			echo $c_theme

			echo -e "\nCURRENTLY AVALIABLE :"
			for ((i=0; $i<$n_themes; i++)) {
				echo -e "$(($i+1)) "$(echo $l_themes | awk "{print \$$(($i+1))}")
			}

			echo; read -p "choose (1-$n_themes): " n_chose
			for ((i=0; $i<$n_themes; i++)) {
				if [[ $(($i+1)) == $n_chose ]]; then
					__success__=1
					break
				fi
			}
			if [[ $__success__ ]]; then
				break
			fi

			echo -e "\ntry again."
			sleep 2;
		}

		update-alternatives --set default.plymouth $themesdir/$(echo $l_themes | awk "{print \$$n_chose}") > /dev/null && \
		echo -e "\nchanging setting : SUCCESS"
	fi
	_u_initramfs
else

  ####    FOR NOT USE ALTERNATIVES    ####

	if [ -e $themesdir/default.plymouth ]; then
		mv $themesdir/default.plymouth $themesdir/default.plymouth.bak.serene
		echo "default.plymouth file was backuped."
	fi

	for ((;;)) {
		echo 'what theme in /usr/share/plymouth/themes do u want to use?  (ex."serene-logo/serene-logo.plymouth"'
		read t_name
		if [ -e $themesdir/$t_name ]; then
			echo "plymouth theme found."
			ln -sf $themesdir/$t_name $themesdir/default.plymouth
			break
		fi
		echo -e "could not found such a theme...\n"
	}

fi
