#!/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
}



install_poweroff_user()
{
	local needs_po=false
	local group="admin"
	local po_user=
	local po_pass=
	local po_cmd=
	local sudofile="/etc/sudoers.d/ku-poweroff"
	local tmp="ku-poweroff.tmp"

	class_requested server			&& needs_po=true
	getconfirm system.poweroff_enabled	&& needs_po=true
	$needs_po || {
		uninstallfiles --remove $sudofile
		return 0
	}

	po_user=$(jtconf system.poweroff_user 2>/dev/null) || :		# optional
	po_pass=$(jtconf system.poweroff_password 2>/dev/null) || :	# optional
	po_cmd=$(jtconf system.poweroff_command 2>/dev/null) || :	# optional
	po_home=$(jtconf system.poweroff_home 2>/dev/null) || :		# optional
	po_shell=$(jtconf system.poweroff_shell 2>/dev/null) || :	# optional

	po_cmd=${po_cmd:-/usr/sbin/safe_poweroff}
	po_home=${po_home:-/var/run}
	po_shell=${po_shell:-$po_cmd}

	# user or password undefined, don't install
	[ "X$po_user" = "X" -o "X$po_pass" = "X" ] && return 0

	nscd_refresh

	if getent passwd $po_user >/dev/null
	then
		echo "  updating poweroff user '$po_user:$group' ..."
			usermod \
				--gid $group --home $po_home --shell $po_shell \
				--comment "kusa poweroff user" \
				$po_user
	else
		echo "  adding poweroff user '$po_user:$group' ..."
			useradd --system \
				--gid $group --home $po_home --shell $po_shell \
				--comment "kusa poweroff user" \
				$po_user
	fi

	nscd_refresh

	echo "  setting password for the poweroff user: $po_user"
	echo "$po_user:$po_pass" | chpasswd

	echo "# ::do_not_edit::" >$tmp
	echo "# crated by kusa from module 'base'" >>$tmp
	echo "%$group	ALL=NOPASSWD: $po_cmd" >>$tmp

	installfile $tmp $sudofile root:root 440

	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
#
install_poweroff_user





# /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)
  	;;
  *)
	# 2024-03-07
	# - /etc/localtime is a symlink, no more a file
	if [ -L /etc/localtime ]
	then
		here=$(pwd)
		share="/usr/share/zoneinfo"
		cd /etc
		case $timezone in
		  CH)	tzfile="Europe/Zurich" ;;
		  IT)	tzfile="Europe/Rome" ;;
		esac
		rm -f localtime; ln -s /usr/share/zoneinfo/$tzfile localtime
		echo "  installed /etc/localtime: $tzfile"
		cd "$here"
	else
		installfile "localtime-$timezone" /etc/localtime root:root 444 false
	fi
	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

# 2023-10-24 lc fixes missing /etc/debian_version
#
[ -f /etc/debian_version ] || {
	case $DISTRIB_CODENAME in
	  jessie)	ver=8 ;;
	  ascii)	ver=9 ;;
	  beowulf)	ver=10 ;;
	  chimaera)	ver=11 ;;
	  daedalus)	ver=12 ;;
	  excalibur)	ver=13 ;;
	esac
	echo "  WARNING: fix missing /etc/debian_version -> $ver (devuan=$DISTRIB_CODENAME)"
	echo $ver >/etc/debian_version
	chmod 640 /etc/debian_version
	#SOMETHING_CHANGED=true		# no, don't want to trig this
}



# 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

# 2025-12-10 lc quiet hd io, for NAS and like
#
file="76-ku-quiet-disk-io.conf"
dir="/etc/sysctl.d"

if getconfirm common.quiet_disk_io
then
	installfile $file $dir/ root:root 444
else
	uninstallfiles $dir/$file
fi

# 2026-08-03
#
[ -f /root/.vimrc ] || {
	installfile vimrc /root/.vimrc root:root 550
}


$SOMETHING_CHANGED && {

	# 2025-12-10 lc set vm.swappiness to reduce SSD usage
	#
	in_chroot || {
		# in case we have changed sysctl files ...
		#
		# 2025-12-31 lc fix: error if no files
		ls /etc/sysctl.d/*.conf 2>/dev/null | xargs -n 1 --no-run-if-empty /sbin/sysctl -p
	}
}

exit 0
