###########################
## Pre-Install functions ##
###########################

update_default_user() {

	# Make sure there is a qubes group
	groupadd --force --system --gid 98 qubes

	# Archlinux bash version has a 'bug' when running su -c, /etc/profile is not loaded because bash consider there is no interactive pty when running 'su - user -c' or something like this.
	# See https://bugs.archlinux.org/task/31831
	id -u 'user' >/dev/null 2>&1 || {
	  useradd --user-group --create-home --shell /bin/zsh user
	}
	usermod -a --groups qubes user

}

## arg 1:  the new package version
pre_install() {
	echo "Pre install..."

	update_default_user

	# do this whole %pre thing only when updating for the first time...

	mkdir -p /var/lib/qubes

	# Backup fstab / But use archlinux defaults (cp instead of mv)
	if [ -e /etc/fstab ] ; then
		cp /etc/fstab /var/lib/qubes/fstab.orig
	fi

	# Add qubes core related fstab entries
	echo "xen	/proc/xen	xenfs	defaults	0 0" >> /etc/fstab

	usermod -p '' root
	usermod -L user
}


## arg 1:  the new package version
## arg 2:  the old package version
pre_upgrade() {
	# do something here
	echo "Pre upgrade..."

	update_default_user

}

###################
## Install Hooks ##
###################


configure_notification-daemon() {
    # Enable autostart of notification-daemon when installed
    if [ ! -e /etc/xdg/autostart/notification-daemon.desktop ]; then
        ln -s /usr/share/applications/notification-daemon.desktop /etc/xdg/autostart/
    fi
}

configure_selinux() {

	# SELinux is not enabled on archlinux
	#echo "--> Disabling SELinux..."
	echo "SELINUX not enabled on archlinux. skipped."
	# sed -e s/^SELINUX=.*$/SELINUX=disabled/ -i /etc/selinux/config
	# setenforce 0 2>/dev/null

}

############################
## Post-Install functions ##
############################

update_qubesconfig() {

	# Create NetworkManager configuration if we do not have it
	if ! [ -e /etc/NetworkManager/NetworkManager.conf ]; then
	echo '[main]' > /etc/NetworkManager/NetworkManager.conf
	echo 'plugins = keyfile' >> /etc/NetworkManager/NetworkManager.conf
	echo '[keyfile]' >> /etc/NetworkManager/NetworkManager.conf
	fi
	/usr/lib/qubes/qubes-fix-nm-conf.sh

	# Remove ip_forward setting from sysctl, so NM will not reset it
	# Archlinux now use sysctl.d/ instead of sysctl.conf
	#sed 's/^net.ipv4.ip_forward.*/#\0/'  -i /etc/sysctl.conf

	# Remove old firmware updates link
	if [ -L /lib/firmware/updates ]; then
	  rm -f /lib/firmware/updates
	fi

	# Yum proxy configuration is fedora specific
	#if ! grep -q '/etc/yum\.conf\.d/qubes-proxy\.conf' /etc/yum.conf; then
	#  echo >> /etc/yum.conf
	#  echo '# Yum does not support inclusion of config dir...' >> /etc/yum.conf
	#  echo 'include=file:///etc/yum.conf.d/qubes-proxy.conf' >> /etc/yum.conf
	#fi

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

	# qubes-core-vm has been broken for some time - it overrides /etc/hosts; restore original content
	if ! grep -rq "^/etc/hosts$" "${PROTECTED_FILE_LIST}" 2>/dev/null; then
	    if ! grep -q localhost /etc/hosts; then
	      cat <<EOF > /etc/hosts
	127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4 `hostname`
	::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
EOF
	    fi
	fi

	# ensure that hostname resolves to 127.0.0.1 resp. ::1 and that /etc/hosts is
	# in the form expected by qubes-sysinit.sh
	if ! grep -rq "^/etc/hostname$" "${PROTECTED_FILE_LIST}" 2>/dev/null; then
	    for ip in '127\.0\.0\.1' '::1'; do
	        if grep -q "^${ip}\(\s\|$\)" /etc/hosts; then
	            sed -i "/^${ip}\s/,+0s/\(\s`hostname`\)\+\(\s\|$\)/\2/g" /etc/hosts
	            sed -i "s/^${ip}\(\s\|$\).*$/\0 `hostname`/" /etc/hosts
	        else
	            echo "${ip} `hostname`" >> /etc/hosts
	        fi
	    done
	fi

	# Make sure there is a default locale set so gnome-terminal will start
	if [ ! -e /etc/locale.conf ] || ! grep -q LANG /etc/locale.conf; then
	    touch /etc/locale.conf
	    echo "LANG=en_US.UTF-8" >> /etc/locale.conf
	fi
	# ... and make sure it is really generated
	# This line is buggy as LANG can be set to LANG="en_US.UTF-8". The Quotes must be stripped
	current_locale=`grep LANG /etc/locale.conf|cut -f 2 -d = | tr -d '"'`
	if [ -n "$current_locale" ] && ! locale -a | grep -q "$current_locale"; then
	    base=`echo "$current_locale" | cut -f 1 -d .`
	    charmap=`echo "$current_locale.UTF-8" | cut -f 2 -d .`
	    [ -n "$charmap" ] && charmap="-f $charmap"
	    localedef -i $base $charmap $current_locale
	fi

}

configure_systemd() {

PRESET_FAILED=0

if [ $1 -eq 1 ]; then
    # Needs to be started two times to deal  with services name changes (systemctl bug?)
    echo "Resetting systemd services to defaults presets (PASS 1)"
    systemctl --no-reload preset-all 2>&1 && PRESET_FAILED=0 || PRESET_FAILED=1
    echo "Resetting systemd services to defaults presets (PASS 2)"
    systemctl --no-reload preset-all 2>&1 && PRESET_FAILED=0 || PRESET_FAILED=1
else
    services="qubes-dvm qubes-misc-post qubes-firewall qubes-mount-dirs"
    services="$services qubes-netwatcher qubes-network qubes-sysinit"
    services="$services qubes-iptables qubes-updates-proxy qubes-qrexec-agent"
    services="$services qubes-random-seed"
    for srv in $services; do
        echo "Enable service defaults for $service"
        systemctl --no-reload preset $srv.service
    done
    systemctl --no-reload preset qubes-update-check.timer
    # Upgrade path - now qubes-iptables is used instead
    systemctl --no-reload preset iptables.service
    systemctl --no-reload preset ip6tables.service
fi

# Set default "runlevel"
rm -f /etc/systemd/system/default.target
ln -s /lib/systemd/system/multi-user.target /etc/systemd/system/default.target

grep '^[[:space:]]*[^#;]' /lib/systemd/system-preset/75-qubes-vm.preset | while read action unit_name; do
    case "$action" in
    (disable)
        if [ -f /lib/systemd/system/$unit_name ]; then
            if ! fgrep -q '[Install]' /lib/systemd/system/$unit_name; then
                # forcibly disable
                ln -sf /dev/null /etc/systemd/system/$unit_name
            fi
        fi
        ;;
    *)
        # preset-all is not available in fc20; so preset each unit file listed in 75-qubes-vm.preset
        if [ $1 -eq 1 -a "${PRESET_FAILED}" -eq 1 ]; then
            systemctl --no-reload preset "${unit_name}" > /dev/null 2>&1 || true
        fi
        ;;
    esac
done

systemctl daemon-reload

}

config_prependtomark() {
FILE=$1
APPENDBEFORELINE=$2
APPENDLINE=$3
grep -q "$APPENDLINE" "$FILE" || sed "/$APPENDBEFORELINE/i$APPENDLINE" -i "$FILE"
}

config_appendtomark() {
FILE=$1
APPENDAFTERLINE=$2
APPENDLINE=$3
grep -q "$APPENDLINE" "$FILE" || sed "/$APPENDAFTERLINE/a$APPENDLINE" -i "$FILE"
}

update_finalize() {

	# Archlinux specific: Update pam.d configuration for su to enable systemd-login wrapper
	if [ -z "`cat /etc/pam.d/su | grep system-login`" ] ; then
		echo "Fixing pam.d"
		sed '/auth\t\trequired\tpam_unix.so/aauth\t\tinclude\t\tsystem-login' -i /etc/pam.d/su
		sed '/account\t\trequired\tpam_unix.so/aaccount\t\tinclude\t\tsystem-login' -i /etc/pam.d/su
		sed '/session\t\trequired\tpam_unix.so/asession\t\tinclude\t\tsystem-login' -i /etc/pam.d/su
		cp /etc/pam.d/su /etc/pam.d/su-l
	fi

	# Archlinux specific: ensure tty1 is enabled
	rm -f /etc/systemd/system/getty.target.wants/getty@tty*.service
	systemctl enable getty\@tty1.service

	# Archlinux specific: Prepare pacman.conf to add qubes specific config
	QUBES_MARKER="### QUBES CONFIG MARKER ###"
	config_prependtomark "/etc/pacman.conf" "# REPOSITORIES" "$QUBES_MARKER"
	
	# Add Qubes setup script markers at the right place (this won't work at the end of pacman.conf)"
	config_appendtomark "/etc/pacman.conf" "$QUBES_MARKER" "### QUBES END ###"
	config_appendtomark "/etc/pacman.conf" "$QUBES_MARKER" "### QUBES BEGIN ###"
	
	systemctl daemon-reload
}

## arg 1:  the new package version
post_install() {

	update_qubesconfig

	# do the rest of %post thing only when updating for the first time...
	if [ -e /etc/init/serial.conf ] && ! [ -f /var/lib/qubes/serial.orig ] ; then
		cp /etc/init/serial.conf /var/lib/qubes/serial.orig
	fi

	# Remove most of the udev scripts to speed up the VM boot time
	# Just leave the xen* scripts, that are needed if this VM was
	# ever used as a net backend (e.g. as a VPN domain in the future)
	#echo "--> Removing unnecessary udev scripts..."
	mkdir -p /var/lib/qubes/removed-udev-scripts
	for f in /etc/udev/rules.d/*
	do
	    if [ $(basename $f) == "xen-backend.rules" ] ; then
	        continue
	    fi

	    if [ $(basename $f) == "50-qubes-misc.rules" ] ; then
	        continue
	    fi

	    if echo $f | grep -q qubes; then
	        continue
	    fi

	    mv $f /var/lib/qubes/removed-udev-scripts/
	done

	mkdir -p /rw

	configure_notification-daemon
	configure_selinux

	configure_systemd 0

	update_finalize

	glib-compile-schemas /usr/share/glib-2.0/schemas &> /dev/null || :
	
}

## arg 1:  the new package version
## arg 2:  the old package version
post_upgrade() {

	update_qubesconfig

	configure_notification-daemon
	configure_selinux

	configure_systemd 1

	update_finalize

	/usr/bin/glib-compile-schemas /usr/share/glib-2.0/schemas &> /dev/null || :

}

######################
## Remove functions ##
######################

## arg 1:  the old package version
pre_remove() {

    # no more packages left
    if [ -e /var/lib/qubes/fstab.orig ] ; then
    mv /var/lib/qubes/fstab.orig /etc/fstab
    fi
    mv /var/lib/qubes/removed-udev-scripts/* /etc/udev/rules.d/
    if [ -e /var/lib/qubes/serial.orig ] ; then
    mv /var/lib/qubes/serial.orig /etc/init/serial.conf
    fi

}

## arg 1:  the old package version
post_remove() {

    /usr/bin/glib-compile-schemas /usr/share/glib-2.0/schemas &> /dev/null || :

    if [ -L /lib/firmware/updates ] ; then
      rm /lib/firmware/updates
    fi

    rm -rf /var/lib/qubes/xdg

    for srv in qubes-dvm qubes-sysinit qubes-misc-post qubes-mount-dirs qubes-netwatcher qubes-network qubes-qrexec-agent; do
        systemctl disable $srv.service
    done
    
}