#!/bin/bash

### BEGIN INIT INFO
# Provides:          hobot
# Required-Start:    $all
# Required-Stop:
# Default-Start:     2 3 4 5
# Default-Stop:
# Short-Description: Some configurations when the system starts for the first time
### END INIT INFO

do_first_run()
{
	if [ -f /etc/.do_first_run ];then

		depmod -a $(uname -r)
		ldconfig

		ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime

		# Configure hobot ubuntu desktop
		# Debian Buster desktop bugfix https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=923289
		systemctl status lightdm > /dev/null 2>&1
		if [ $? -ne 4 ];then
			[[ -d /etc/lightdm ]] && dpkg-reconfigure libgdk-pixbuf2.0-0 && update-mime-database /usr/share/mime

			[[ -n "$(systemctl status lightdm | grep 'active')" ]] && [[ -d /etc/lightdm ]] && dpkg-reconfigure lightdm && systemctl restart lightdm
		fi

		if [ -d /home/sunrise/.config ];then
			echo "Configuring sunrise/.config"
			chown -R sunrise:sunrise /home/sunrise/.config
			find /home/sunrise/.config -type d -exec chmod u+x {} \;
		fi

		if [ -d /home/sunrise/.local ];then
			echo "Configuring sunrise/.local"
			chown -R sunrise:sunrise /home/sunrise/.local
			find /home/sunrise/.local -type d -exec chmod +x {} \;
		fi

		echo "Configuring sunrise/Desktop"
		chmod -R +x /home/sunrise/Desktop

		# Add dbus-daemon-launch-helper permissions and ownership settings
		chown root:messagebus /usr/lib/dbus-1.0/dbus-daemon-launch-helper
		chmod 4754 /usr/lib/dbus-1.0/dbus-daemon-launch-helper
		dpkg-reconfigure polkitd

		# Fix permission(Add setuid permission) and ownership
		chmod 4755 /usr/lib/snapd/snap-confine
		chmod 4755 /usr/lib/openssh/ssh-keysign
		chmod 4755 /usr/bin/{chfn,passwd,sudo,pkexec,newgrp,umount,gpasswd,chsh,fusermount3,mount,su}
		chown root:shadow /etc/shadow

		# Configure hobot-ethercat
		dpkg-reconfigure hobot-ethercat

		rm -rf /etc/.do_first_run
	fi
}

case "$1" in
	start)
		do_first_run && systemctl disable hobot-firstrun
		exit 0
		;;
	stop)
		exit 0
		;;
	restart)
		do_first_run && systemctl disable hobot-firstrun
		exit 0
		;;
	*)
		do_first_run && systemctl disable hobot-firstrun
		exit 0
		;;
esac
