#!/bin/bash

info() {
	echo "$(basename $0): $*"
}

warn() {
	echo >&2 "$(basename $0): warning, $*"
}

usage() {
	echo >&2 "usage: $(basename $0) --apply <service> [<service> ...]"
}

if [ "$UID" != "0" ]; then
	warn "need to be root, aborting"
	exit 1
fi

if [ $# -lt 2 ]; then
	usage
	exit 1
fi

database_lookup() {
	local service unused

	# 'priority' field is not used but is kept for backward compat reason.
	while read service unused; do
		if [ $service == $1 ]; then
			return 0
		fi
	done </var/lib/systemd/sysv-convert/database

	return 1
}

database_add() {
	# Write a dumb priority as it is not used.
	echo "$1	$2 50" >>/var/lib/systemd/sysv-convert/database
}

# Initialize the database.
if [ ! -e /var/lib/systemd/sysv-convert/database ]; then
	touch /var/lib/systemd/sysv-convert/database
fi

case "$1" in
--save)
	# --save is kept for backward compatibility.
	;;
--apply)
	shift
	for service in $@; do
		# For backward compat we accept the name of the
		# service with or without the unit type suffix. If the
		# suffix is not there, assume .service type.
		case "$service" in
		*.*)	initscript="${service%.*}" ;;
		*)	initscript="$service"
			service="$service.service"
		esac

		# Did we already migrate this service during a previous update ?
		database_lookup $initscript &&
			continue

		# Sanity check.
		unit="/usr/lib/systemd/system/$service"
		if [ ! -f "$unit" ]; then
			warn "$unit not found, skipping"
			continue
		fi

		# Mark the service as processed to make sure we will do the migration only
		# once. This is important especially for packages that keep their init
		# scripts around even if they're no more used. Since the saved info won't
		# be reused again we simply use an invalid runlevel and add the service
		# in the db only once.
		database_add $initscript -1

		# Some services were renamed during the transition from SySV init to
		# systemd (bsc#1181788). Rather than letting packages fixing that
		# themselves by hacking our database directly, let's hard-code renames
		# here. Not really nice but that's the least worst solution.
		case $initscript in
		ntpd)	initscript=ntp ;;
		esac

		# The package is introducing new services and never has any sysv init
		# scripts (bsc#982303).
		if [ ! -r /etc/init.d/$initscript ] &&
		   [ ! -r /etc/init.d/boot.$initscript ]; then
			continue
		fi

		for rcnd in rc2.d rc3.d rc4.d rc5.d boot.d; do
			# Was the sysvinit script enabled ? (bsc#982211)
			case $rcnd in
			boot.d)	[ -L /etc/init.d/boot.d/S??boot.$initscript ] || continue ;;
			*)	[ -L /etc/init.d/$rcnd/S??$initscript ] || continue
			esac

			case $rcnd in
			boot.d)	runlevel=3 ;;
			*)	runlevel=${rcnd:2:1}
			esac

			target=runlevel$runlevel.target
			info "enabling $unit (wanted by $target)..."

			mkdir -p "/etc/systemd/system/$target.wants"
			ln -sf $unit /etc/systemd/system/$target.wants/$service
		done
	done
	;;
*)
	usage
	exit 1
esac
