#!/bin/bash
#
# chkconfig: 345 90 90
# description: Executes Qubes core scripts at VM boot
#
# Source function library.
. /etc/rc.d/init.d/functions

start()
{
	echo -n $"Executing Qubes Core scripts:"

	# Set permissions to /proc/xen/xenbus, so normal user can access xenstore
	chmod 666 /proc/xen/xenbus
	# Set permissions to files needed by gui-agent
	chmod 666 /proc/u2mfn

	mkdir -p /var/run/xen-hotplug
	mkdir -p /var/run/qubes
	chgrp qubes /var/run/qubes
	chmod 0775 /var/run/qubes

	# Load random seed from dom0
	qubesdb-read /qubes-random-seed | base64 -d > /dev/urandom
	qubesdb-rm /qubes-random-seed

	# Location of files which contains list of protected files
	PROTECTED_FILE_LIST='/etc/qubes/protected-files.d'

	# Set the hostname
	if ! grep -rq "^/etc/hostname$" "${PROTECTED_FILE_LIST}" 2>/dev/null; then
		name=$(/usr/bin/qubesdb-read /name)
		if ! [ -f /etc/this-is-dvm ] ; then
			# we don't want to set hostname for DispVM
			# because it makes some of the pre-created dotfiles invalid (e.g. .kde/cache-<hostname>)
			# (let's be frank: nobody's gonna use xterm on DispVM)
			hostname $name
			sed -i "s/^\(127\.0\.0\.1[\t ].*\) \($name \)\?\(.*\)/\1\2 $name/" /etc/hosts
		fi
	fi

	# Set the timezone
	if ! grep -rq "^/etc/timezone$" "${PROTECTED_FILE_LIST}" 2>/dev/null; then
		timezone=`/usr/bin/qubesdb-read /qubes-timezone 2> /dev/null`
		if [ -n "$timezone" ]; then
			ln -f /usr/share/zoneinfo/$timezone /etc/localtime
			echo "# Clock configuration autogenerated based on Qubes dom0 settings" > /etc/sysconfig/clock
			echo "ZONE=\"$timezone\"" >> /etc/sysconfig/clock
		fi
	fi

	/usr/lib/qubes/update-proxy-configs

	# Set IP address again (besides action in udev rules); this is needed by
	# DispVM (to override DispVM-template IP) and in case when qubes-ip was
	# called by udev before loading evtchn kernel module - in which case
	# qubesdb-read fails
	INTERFACE=eth0 /usr/lib/qubes/setup-ip

	if [ -e /dev/xvdb ] ; then
		# check if private.img (xvdb) is empty - all zeros
		private_size_512=`blockdev --getsz /dev/xvdb`
		if dd if=/dev/zero bs=512 count=$private_size_512 | diff /dev/xvdb - >/dev/null; then
			# the device is empty, create filesystem
			echo "--> Virgin boot of the VM: creating filesystem on private.img"
			mkfs.ext4 -m 0 -q /dev/xvdb || exit 1
		fi

		mount /rw
		resize2fs /dev/xvdb 2> /dev/null || echo "'resize2fs /dev/xvdb' failed"

        if ! [ -d /rw/home ] ; then
        	echo
        	echo "--> Virgin boot of the VM: Linking /home to /rw/home"

        	mkdir -p /rw/config
		cat > /rw/config/rc.local <<EOF
#!/bin/sh

# This script will be executed at every VM startup, you can place your own
# custom commands here. This include overriding some configuration in /etc,
# starting services etc.
#
# You need to make this script executable to have it enabled.

# Example for overriding the whole CUPS configuration:
#  rm -rf /etc/cups
#  ln -s /rw/config/cups /etc/cups
#  systemctl --no-block restart cups
EOF

			touch /rw/config/qubes-firewall-user-script
			cat > /rw/config/qubes-firewall-user-script <<EOF
#!/bin/sh

# This script is called in ProxyVM after firewall every update (configuration
# change, starting some VM etc). This is good place to write own custom
# firewall rules, in addition to autogenerated one. Remember that in most cases
# you'll need to insert the rules at the beginning (iptables -I) to have it
# efective.
#
# You need to make this script executable to have it enabled.
EOF

			touch /rw/config/suspend-module-blacklist
			cat > /rw/config/suspend-module-blacklist <<EOF
# You can list here modules you want to be unloaded before going to sleep. This
# file is used only if the VM has any PCI device assigned. Modules will be
# automatically loaded after resume.
EOF

            mkdir -p /rw/home
            cp -a /home.orig/user /rw/home

            mkdir -p /rw/usrlocal
            cp -a /usr/local.orig/* /rw/usrlocal

            touch /var/lib/qubes/first-boot-completed
        fi
	fi
    if [ -L /home ]; then
        rm /home
        mkdir /home
    fi
    mount /home

	[ -x /rw/config/rc.local ] && /rw/config/rc.local

	success
	echo ""

	start_ntpd=$(/usr/bin/qubesdb-read /qubes-service/ntpd 2> /dev/null)
	if [ "$start_ntpd" == "1" ]; then
		/sbin/service ntpd start
	fi
	return 0
}

stop()
{
	su -c 'mkdir -p /home_volatile/user/.local/share/applications' user
	su -c 'cp -a /usr/share/applications/defaults.list /home_volatile/user/.local/share/applications/' user
	if [ -r '/home/user/.local/share/applications/defaults.list' ]; then
		su -c 'cat /home/user/.local/share/applications/defaults.list >> /home_volatile/user/.local/share/applications/defaults.list' user
	fi
	return 0
}

case "$1" in
  start)
	start
	;;
  stop)
	stop
	;;
  *)
	echo $"Usage: $0 {start|stop}"
	exit 3
	;;
esac

exit $RETVAL
