#!/bin/bash

. ${TOOLKIT}-functions.sh

# refresh (invalidate) nscd buffers
nscd_refresh()
{
	$have_nscd || return 0
	nscd --invalidate passwd 2>/dev/null || :
	nscd --invalidate group 2>/dev/null || :
	sleep 1
	return 0
}


# (MAIN)

# 2014.09.30
# restore original dash 
# assure that /bin/sh is correctly linked to bash (and not dash!)
#
dash=false
[ "$(dpkg-divert --list /bin/sh)" == "diversion of /bin/sh to /bin/sh.distrib by dash" ] \
	&& dash=true

$dash && {
	[ -L /bin/sh ] && {
		link=`ls -ls /bin/sh | sed -e 's/.*-> //'`
		[ "$link" != "dash" ] && {
			echo "  restoring original link for /bin/sh -> dash"
			rm -f /bin/sh.original
			rm -f /bin/sh
			(cd /bin ; ln -s dash sh) || exit $?
		}
	}
}


have_nscd=false
is_installed nscd && have_nscd=true

pkgs="nscd"
if getconfirm common.enable_nscd
then
	$have_nscd || install_pkgs $pkgs
	have_nscd=true
else
	$have_nscd && remove_pkgs $pkgs || :
	have_nscd=false
fi

pkgs="avahi-daemon avahi-utils"
if getconfirm common.enable_avahi
then
	is_installed $pkgs || install_pkgs $pkgs
else
	is_installed $pkgs && remove_pkgs $pkgs || :
fi


# install poweroff user (only for server classes)
#
pouser=
popwd=
class_requested server && {
	pouser=`jtconf system.poweroff_user 2>/dev/null` || :		# optional
	popwd=`jtconf system.poweroff_password 2>/dev/null` || :	# optional
}
[ X"$pouser" != "" ] && {
	cmd="/sbin/safe_poweroff"
	group="admin"

	nscd_refresh

	getent passwd $pouser >/dev/null || {
		echo "  adding poweroff user '$pouser:$group' to system .."
		useradd --system \
			--gid $group \
			--home /var/run \
			--shell $cmd \
			--comment "poweroff user" \
			$pouser
		nscd_refresh
	}
	if [ X"$popwd" == "X" ]
	then
		putwarning "poweroff user: $pouser" \
			"You have not assigned a password to the" \
			"poweroff user '$pouser', you must assign" \
			"one to use it."
	else
		echo "  updating password for the poweroff user: $pouser"
		echo "$pouser:$popwd" | chpasswd
	fi
	grep -q "$cmd" /etc/sudoers || {
		echo "  adding '$cmd' for group '$group' in /etc/sudoers .."
		echo "" >>/etc/sudoers
		echo "#[ku] added by kusa on `date`" >>/etc/sudoers
		echo "%$group	ALL=NOPASSWD: $cmd" >>/etc/sudoers
		echo "" >>/etc/sudoers
	}
}




# /home relocation?
#
home=`jtconf path.homes`
link="(none)"

[ "$home" != "/home" ] && {	# not the standard location
	[ -L /home ] && link=`readlink /home`
	if [ "$link" != $home ]
	then
		putwarning "HOME Relocation" \
			"home directory /home, now linked to $link," \
			"must be relocated to $home; this can be a time" \
			"consuming task, please wait ..."
		if [ -d $home ]
		then
			putwarning "HOME Relocation" \
				"$home directory already exists! (server migration?) ..." \
				"/home will be renamed to /home.old and a new link will" \
				"be created, please check by hand"
		else
			jtmkpath -f $home root:root 775
			usage=`du -s /home | awk '{ print $1 }'`
			free=`df -Pk $home | tail -1 | awk '{ print $4 }'`
			needed=`expr $usage + 1024`
			[ $free -lt $needed ] && {
				echo "  ERROR: insufficient free space, can't move /home to $home" >&2
				echo "	we need $needed Kb, available $free Kb" >&2
				echo "	Please change path.homes definition or make some room" >&2
				exit 1
			}
			# are on the same device? (get device numbers using stat)
			homefs=`stat --format '%d' /home`
			linkfs=`stat --format '%d' $home`
			if [ $homefs == $linkfs ]
			then
				echo -en "  moving /home to $home (same fs) ... "
				[ "`ls -d /home/* 2>/dev/null`" != "" ] && {
					mv /home/* $home/.
				}
				rmdir /home
				echo "ok"
			else
				echo -en "  moving /home to $home ... (copying) ... "
				mirror --all -f /home $home >$RUNDIR/mirror.out 2>&1 || {
					stat=$?
					echo -e "\nERROR $stat on: mirror --all -f /home $home\n\n"
					cat $RUNDIR/mirror.out
					exit $stat
				}
				echo -en "  (cleaning) ... "
				rm -rf /home
				echo "ok"
			fi
		fi
		(cd / ; updatelink $home home)
	fi
}


# languages
#
case $DISTRIB_FULL_ID in
   Ubuntu*)
	pkgs=
	for lang in `jtconf common.languages`
	do
		pkgs="$pkgs language-pack-$lang"
	done
	install_pkgs $pkgs
	;;
   Devuan*)
   	##putwarning "LANGUAGES (Devuan)" \
		##"Devuan doesn't have language-pack-* packages, skipping"
	;;
esac


# 2020-02-21
# - on EFI systems there is no such dir
#
if [ -d /boot/grub ]
then
	splash=$(jtconf splash_image 2>/dev/null) || :

	[ "X$splash" = "X" ] && {
		splash=$(ku-machine-icon --search --splash) && {
			echo "  using default splash image: $splash"
		}
	}

	if [ "X$splash" != "X" ]
	then
		save_SOMETHING_CHANGED=$SOMETHING_CHANGED
		SOMETHING_CHANGED=false

		case $splash in
		  *.jpg|*.jpeg)	ext="jpg" ;;
		  *.png)	ext="png" ;;
		  *.tga)	ext="tga" ;;
		esac

		# be sure that we have ku-images packages if we want to
		# use one of our stock images
		#
		case $splash in
		  /usr/share/images/ku-splash/*)
			install_pkgs ku-images ;;
		esac
		installfile $splash /boot/grub/ku-splash.$ext root:root 644 false

		# I think that's changed from Ubuntu 11.00, but ok, will be removed ...
		#
		file="/etc/grub.d/05_debian_theme"
		out="$RUNDIR/05_debian_theme"
		[ -f "$file" ] && {
			grep -q "WALLPAPER=" $file && {
				sed -e "s#WALLPAPER=\".*\"#WALLPAPER=\"/boot/grub/ku-splash.$ext\"#" \
					$file > $out
				installfile $out $file root:root 444 false
			}
		}
		
		$SOMETHING_CHANGED && {
			[ -x /usr/sbin/update-grub ] && update-grub
		}
		SOMETHING_CHANGED=$save_SOMETHING_CHANGED
	fi # splash
else
	echo " dir /boot/grub not exists: this system uses an EFI boot?"
fi



# ipgeo settings
#
file=/etc/ipgeo.conf
[ -f $file ] || {
	key=$(jtconf ipgeo.key 2>/dev/null) && {
		echo -e "# /etc/ipgeo.conf\n#\nkey='$key'\nwget_options=''" >$RUNDIR/ipgeo.conf.tmp
		installfile $RUNDIR/ipgeo.conf.tmp $file root:root 664 false
	}
}


# timezone
#
timezone=$(jtconf customer.timezone 2>/dev/null) || {
	timezone=$(jtconf customer.state)
} || :
case $timezone in
  none|manual)
  	;;
  *)
	installfile "localtime-$timezone" /etc/localtime root:root 444 false
	installfile "timezone-$timezone" /etc/timezone root:root 444 false
	;;
esac


# 2017.04.23
# - damn wget defaults, passive doesn't works on many enviroments
#
passive="off"
file="/etc/wgetrc"
[ -f $file ] && {
	getconfirm common.wgetrc_passive_ftp && passive="on"	# default on debian
	now=$(grep "^\s*passive_ftp\s\s*=" $file 2>/dev/null || :)
	now=$(echo "$now" | sed -e 's/.*=\s*//' -e 's/\s*#.*//')

	[ "$now" != "$passive" ] && {
		putwarning "wget passive ftp changed" \
			"wget passive_ftp changed from '$now' to '$passive' in '$file'"

		if [ "$now" != "" ]
		then
			# previously defined, replace original definition
			sed -e "s/^\s*passive_ftp\s\s*=.*/#[ku] changed by kusa-reconf\npassive_ftp = $passive/" \
				$file >$RUNDIR/wgetrc.tmp
		else
			# not previously defined, add at end of file
			cp -a $file $RUNDIR/wgetrc.tmp
			echo >>$RUNDIR/wgetrc.tmp
			echo "#[ku] added by kusa-reconf" >>$RUNDIR/wgetrc.tmp
			echo "passive_ftp = $passive" >>$RUNDIR/wgetrc.tmp
		fi
		installfile $RUNDIR/wgetrc.tmp $file root:root 664 false
	}
}


# 2017.05.28
# pottashit removal is now optional
#
if getconfirm common.enable_pulseaudio
then
	install_pkgs pulseaudio
else
	remove_pkgs pulseaudio
fi


# 2018.07.30
#
# profile.d
# (activated from ku-base package)
#
# those files comes from ku-base package, they should be in place but
# may be not, we try to force kusa to be dependent from a specific version
# of ku-base package for those silly parts, so we make them optionals
# (removed from install file, installed here with a bit of logic)
#
files="
	/etc/profile-post.d,bash-history-timestamp.sh
	/etc/profile-post.d,silent-beep.sh
	/etc/profile-post.d,umask.sh
	/etc/profile-post.d,grep.sh
	/etc/vim,vimrc.local
"
srcdir="/usr/share/doc/ku-base/examples"

for file in $files
do
	dest=$(echo "$file" | cut -d',' -f1)
	file=$(echo "$file" | cut -d',' -f2)

	[ -f "$srcdir/$file" ] && installfile "$srcdir/$file" "$dest/" root:root 644
done



# sudo
#
[ -f /etc/sudoers.d/README ] || {
	# changes are ininfluent here
	save_SOMETHING_CHANGED=$SOMETHING_CHANGED
	installfile README.sudo /etc/sudoers.d/README root:root 0440
	SOMETHING_CHANGED=save_SOMETHING_CHANGED
}


# this cannot be removed from pkgs-remove file, because we need to install
# an alternative BEFORE removing it, or many basic system packages will be
# removed, too
#
remove_pkgs mawk


# 2020.06.04 lc
# - init.d stuffs need to be manually installed, because have different
#   versions related to system releases
#
for file in $(ls init.d | sed -e 's/\..*//' -e 's/__.*//' | sort -u)
do
	installfile init.d/$file /etc/init.d/$file root:root 0555
	$SOMETHING_CHANGED && {
		update-rc.d $file defaults || exit_err $?
	}
done


# 2021.03.22 lc
# - this shit is not present in all distros, but is needed by some
#   recent softwares (requires dbus, desktop only?)
#
here=$(pwd)
cd /etc
file="machine-id"
src="../var/lib/dbus/$file"

[ -e $file ] || {
	[ -e $src ] && {
		echo "  notice: linking $file -> $src (in /etc)"
		cd /etc
		ln -s "$src" "$file"
	}
}
cd "$here"


# 2022-07-08 lc vimrc fix
#
for file in $(ls vim*-defaults.vim)
do
	version=${file/-defaults.vim/}
	dest="/usr/share/vim/${version}"
	[ -d "$dest" ] && {
		installfile "$file" "$dest/defaults.vim" root:root 444
	}
done


# cleanup old stuffs
#
purgefiles \
	/etc/cron.daily/timesync \
	/etc/rc*.d/???var-tmpfs.sh \
	/etc/init.d/var-tmpfs.sh \
	/etc/profile-post.d/direxpand.sh


##$SOMETHING_CHANGED && {
	##:
##}

exit 0
