#!/bin/bash
my_dir=$(dirname $0)

image_dir=$(realpath "$my_dir/../..")

confdir_src="$image_dir/lib/systemd/system"
confdir_dst="/lib/systemd/system"

service_name=`echo $1 | sed -s 's/\.service//'`
descriptor_src="${confdir_src}/$service_name.service"
descriptor_dst="${confdir_dst}/$service_name.service"

if ! [ -e "$descriptor_src" ] ; then
    echo "The service configuration file $descriptor_src does not exist."
    echo "Make sure that '$1' is spelled correctly."
    exit 1
fi

if [ -e "$descriptor_dst" ] ; then
    echo "The host system has the configuration file $descriptor_src."
    echo "It is not possible to have identically named upstart services"
    echo "in the host and guest systems".
    echo
    echo "If you do not use the service $1 on the host, you can uninstall it"
    echo "and then rerun this script to export $1 from the guest system."
    echo
    echo "Please see the user's manual to learn about the limitations of"
    echo "the guest and host integration mechanisms."
    exit 1
fi

if [ `readlink ${descriptor_src}` == "/dev/null" ] ; then
	ln -s /dev/null ${descriptor_dst}
else 
	transformed=$(mktemp)

	cat - > "$transformed" <<END_OF_PROLOGUE
# This file represents the service $1 in the guest system $image_dir.
# Automatically generated from the file $descriptor_src.
# Do not edit this file.
#
# $EXAGEAR_GUEST_WRAP_MARKER: MARKER OF THE CONVERTED CONFIGURATION FILE (DO NOT EDIT OR REMOVE)
#

END_OF_PROLOGUE

	cat "$descriptor_src" \
	| $image_dir/.exagear/upstart-integration/systemd-line-converter $image_dir/.exagear/upstart_wrapper \
	>> $transformed

	install -m 0644 "$transformed" "$descriptor_dst"

fi

for suffix in "path" "socket"
do
	descriptor_src="${confdir_src}/${service_name}.${suffix}"
	descriptor_dst="${confdir_dst}/${service_name}.${suffix}"

	if ! [ -e "$descriptor_src" ] ; then
	    continue
	fi

	if [ -e "$descriptor_dst" ] ; then
	    continue
	fi

	transformed=$(mktemp)

	cat - > "$transformed" <<END_OF_PROLOGUE
# This file represents the service $1 in the guest system $image_dir.
# Automatically generated from the file $descriptor_src.
# Do not edit this file.
#
# $EXAGEAR_GUEST_WRAP_MARKER: MARKER OF THE CONVERTED CONFIGURATION FILE (DO NOT EDIT OR REMOVE)
#

END_OF_PROLOGUE

	cat "$descriptor_src" >> $transformed

	install -m 0644 "$transformed" "$descriptor_dst"
done

/bin/systemctl daemon-reload
