#!/bin/bash
#---------------------------------------------------------------
# Project         : Mageia Linux
# Module          : rpm-helper
# File            : add-service
# Version         : $Id$
# Authors         : Frederic Lepied, Andrey Borzenkov
# Created On      : Mon Jul  8 08:14:34 2002
# Purpose         : helper script for rpm scriptlets to add a
#                   service.
#---------------------------------------------------------------

if [ "x$1" = x--no-sysv ]; then
    do_sysv=no
    shift
else
    do_sysv=yes
fi

if [ $# -lt 3 ]; then
    echo "usage: $0 [--no-sysv] <pkg name> <number installed> [<service name>] [<unit name> ...]" 1>&2
    exit 1
fi

SYSTEMCTL=/sbin/systemctl
# What init system are we currently using?
if [ -d /run/systemd/system/ ]; then
    init=systemd
else
    init=sysvinit
fi

pkg=$1				# name of the package
num=$2				# number of packages installed
if [ $do_sysv = yes ]; then
    srv=$3			# name of the SysV script
    shift 3
else
    srv=
    shift 2
fi
units="$*"			# systemd units
units_to_enable=		# units enabled by msec

USERUNITDIR=/etc/systemd/system
RUNTIMEUNITDIR=/run/systemd/system
SYSTEMUNITDIR=/lib/systemd/system

find_unit() {
    unit=$(basename "$1")

    # We need to normalise the systemd unit name as the native unit may not have
    # the same filename (sans it's .service suffix) as sysvinit script.
    # In this case, symlinks are used to mask the sysvinit file, but for enabling
    # and disabling units we must use the official name.

    searchunit=
    if [ -L "$USERUNITDIR/$unit" ]; then
        searchunit=$(/bin/readlink -m "$USERUNITDIR/$unit")
    elif [ -e "$USERUNITDIR/$unit" ]; then
        searchunit="$USERUNITDIR/$unit"
    elif [ -L "$RUNTIMEUNITDIR/$unit" ]; then
        searchunit=$(/bin/readlink -m "$RUNTIMEUNITDIR/$unit")
    elif [ -e "$RUNTIMEUNITDIR/$unit" ]; then
        searchunit="$RUNTIMEUNITDIR/$unit"
    elif [ -L "$SYSTEMUNITDIR/$unit" ]; then
        searchunit=$(/bin/readlink -m "$SYSTEMUNITDIR/$unit")
    elif [ -e "$SYSTEMUNITDIR/$unit" ]; then
        searchunit="$SYSTEMUNITDIR/$unit"
    fi
    if [ -n "$searchunit" ]; then
        echo -n "$searchunit"
    fi
}


# If only a sysvinit service is given, then deal with a systemd unit of the same
# name. Specific specs can enable specific unit names as needed but this should
# catch the most common usage.
if [ -z "$units" ] && [ -n "$srv" ] && [ ! -f "/etc/xinetd.d/$srv" ]; then
  units="$srv.service"
  searchunit=$(find_unit $units)
  if [ -n "$searchunit" ]; then
    units=$(basename "$searchunit")
  fi
fi

add_service() {
        units_to_enable="$units"

    # Actually do enable/disable foo
    if [ -n "$units_to_enable" ]; then
        # Prefer preset (for native systemd units), but fall back to enable (for sysvinit units)
        $SYSTEMCTL --quiet preset $units_to_enable >/dev/null 2>&1 || $SYSTEMCTL --quiet enable $units_to_enable >/dev/null 2>&1
        if [ $? -ne 0 ]; then
          echo "Warning: Problems encountered when activating services." >&2
          echo "  Please check and enable manually if necessary." >&2
          echo "  Service units affected: $units_to_enable" >&2
        fi
    fi

    # When no native systemd unit exists, the above command will actually
    # just end up running chkconfig anyway, but if a native systemd unit exists
    # the legacy init script will not be enabled.
    # In order to enable switching back ot sysvinit, we should enable the
    # sysvinit scripts too.
    if [ -n "$srv" ]; then
      if [ -f /etc/rc.d/init.d/$srv ] || [ -f /etc/xinetd.d/$srv ]; then
        /sbin/chkconfig --add $srv

        if [ -r /etc/sysconfig/system ]; then
            . /etc/sysconfig/system
        fi

        # TODO what to do with system units here?
        if [ -z "$ADD_SERVICES_TO_CURRENT_PROFILE_ONLY" ]; then
            # add the service to all the profiles at once
            if [ -d /etc/netprofile/profiles/default/services ]; then
                for dir in /etc/netprofile/profiles/*/services; do
                    touch "$dir/$srv"
                done
            fi
        fi
      fi
    fi
}

check_sysvinit_service() {
    rl=$1
    srv=$2

    set -- /etc/rc${rl}.d/S??$srv
    if [ $# -gt 1 ]; then
        echo 1>&2 "add-service: Error: $srv appears multiple times at runlevel $rl: $*"
    fi

    echo -n "$1"
}
if [ "$num" = 1 ]; then
    # First install mode
    if [ "null" != "$units" ]; then
        add_service
    fi
else
    # Upgrade mode.
    reloaded=no

    if [ "x$init" = xsystemd ]; then
        # Package install may have changed the unit file, so reload the daemon
        # before trying to restart anything
        if [ "x$reloaded" = xno ]; then
            $SYSTEMCTL --system daemon-reload
        fi
        # There may be template units, so attempt to find all instances and
        # restart them.
        for unit in $units; do
            if [[ "$unit" =~ @.service ]]; then
                instances=$($SYSTEMCTL -a --full list-units | grep -E "${unit%@.service}@[^ ]+.service" | awk '{ print $1 }')
                if [ -n "$instances" ]; then
                    for iunit in $instances; do
                        $SYSTEMCTL --quiet try-restart "$iunit"
                    done
                fi
            elif [ "null" != "$unit" ]; then
                $SYSTEMCTL --quiet try-restart "$unit"
            fi
        done
    elif [ -f "/etc/rc.d/init.d/$srv" ]; then
        script=$(check_sysvinit_service 3 "$srv");
        if [ -f "$script" ]; then
            /sbin/chkconfig --add "$srv"
        fi

        # restart the service if already running
        if [ -f "/var/lock/subsys/$srv" ]; then
            /sbin/service "$srv" restart > /dev/null || :
        fi
    fi
fi

# add-service ends here
