#!/bin/sh -e

if test -z "$1" ; then
  echo "svctl-enable: usage: svctl-enable service..." 1>&2
  exit 100
fi

dbx="s6-rc-db -c /usr/lib/s6-rc/compiled-work"

policy=$(readlink /usr/lib/s6-rc/policy/current)
if test x"$policy" = x"exclusive" ; then
  isexclusive=true
elif test x"$policy" = x"shared" ; then
  isexclusive=false
else
  echo "svctl-enable: fatal: /usr/lib/s6-rc/policy/current should be a relative symlink to either shared or exclusive" 1>&2
  exit 100
fi

tmp=$(mktemp /tmp/svctl-enable.XXXXXX)
cleanup () {
  rm -f "$tmp"
}
trap cleanup EXIT TERM INT HUP QUIT ABRT

ls -1 /usr/lib/s6-rc/masked > "$tmp"
if list=$($dbx all-dependencies "$@" | grep -Fx -f "$tmp") ; then
  {
    printf "svctl-enable: fatal: at least one of the listed services has a dependency on the following masked service: "
    echo "$list" | head -n 1
  } 1>&2
  exit 1
fi

cleanup
trap - EXIT TERM INT HUP QUIT ABRT

needcompile=false
for i in $($dbx atomics "$@") ; do
  if test -d "/usr/lib/s6-rc/sources/$i" ; then
    if $isexclusive ; then
      touch "/usr/lib/s6-rc/policy/exclusive/top/contents.d/$i"
    else
      for j in 2 3 4 5 ; do
        touch "/usr/lib/s6-rc/policy/shared/runlevel_$j/contents.d/$i"
      done
    fi
    needcompile=true
  else
    echo "svctl-enable: warning: service $i not found in /usr/lib/s6-rc/sources"
  fi
done

if $needcompile ; then
  exec /usr/lib/s6-policy-common/bin/svctl-compile
fi
