#!/usr/bin/env bash

#: This scriptlet is used to ensure that upstart is able to run 
#: user jobs on this system.  By default upstart user jobs are disabled
#: on Ubuntu 12.04, but enabled on 13.04 so this will first test
#: whether a test job can be created and then run by the specified user.

local TESTUSER=$1
local TESTUSER_EXISTS=$(userExists $TEST_USER)
local TESTSCRIPT=/home/$TESTUSER/.init/testscript.conf

# make sure we've been provided a user
[[ $TESTUSER ]] || abort "To configure upstart user jobs, we require a normal test user, e.g. require upstart-user-jobs <username>"

# ensure that the user exists
[[ $TESTUSER_EXISTS ]] || abort "Unknown user: $TESTUSER"

# make the init folder for the specified user
sudo -u $TESTUSER mkdir -p /home/$TESTUSER/.init

# create a test upstart user script
cat <<SCRIPT > $TESTSCRIPT
task

script
  sleep 0
end script
SCRIPT

# set script owner and permissions
sudo chown $TESTUSER:$TESTUSER $TESTSCRIPT
sudo chmod a+x $TESTSCRIPT

# try running the script
sudo -u $TESTUSER start testscript >/dev/null

# save the exit code
local UPSTART_EXITCODE=$?

# if we could not start the script or the requested file has not been
# created then we probably need to patch the system Upstart.conf file
# to allow user jobs
if [ $UPSTART_EXITCODE != 0 ]; then
  require systemupdate /etc/dbus-1/system.d/Upstart.conf
fi

# include the code required to kick in upstart user jobs on machine start
# see: http://bradleyayers.blogspot.com.au/2012/04/enabling-upstart-user-jobs-to-start-at.html
cat <<'SCRIPT' > /etc/init/load-user-jobs.conf
author 'Bradley Ayers'
description 'Enables user job "start on" stanzas to be honored at boot'
task

# initctl doesn't work before dbus starts
start on started dbus

script
  cat /etc/passwd | while read line; do
    user=`echo $line | cut -d: -f1`
    home=`echo $line | cut -d: -f6`

    if [ -d "$home/.init" ]; then
      echo "sending rc-sysinit for user: $user"
      su $user -c "initctl status rc-sysinit"
    fi
  done

  initctl emit user-jobs
end script
SCRIPT