#!/bin/sh
# Copyright (C) 2012 Jolla Oy
# Contact: Pekka Lundstrom  <pekka.lundstrom@jollamobile.com>
#
# This adds oneshot job to be run later or now
# usage: add-oneshot [--now] [--user] <name of the job> [<more job names>]
# If --now is given, job is run immediately instead of postponing it later
# if instant run fails or if --now is not given, the link is created for later run
# If --user is given, job is run as user, otherwise as root
# Job name is given as name of the executable located in /usr/lib/oneshot.d
# ie. no path mentioned


[ -z "$1" ] && echo "add-oneshot: No jobs defined - FAIL" && exit 1

# Define PATH in case we are called in build time (PATH empty or sbin not included)
if [ -z "$PATH" ] ||
   [[ "$PATH" != *sbin* ]]; then
    PATH="/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin"
fi

set +e
RUN_NOW=""
AS_USER=""

while [ -n "$1" ]; do
    [ "$1" == "--now" ] && RUN_NOW=1 && shift && continue
    [ "$1" == "--user" ] && AS_USER=1 && shift && continue
    # skip execution when called during bootstrap
    [ -f "/.bootstrap" ] && RUN_NOW=
    JOB=$1
    # Job must be located in oneshot dir and must be ok to run it
    [ ! -x /usr/lib/oneshot.d/$JOB ] && echo "add-oneshot: /usr/lib/oneshot.d/$JOB does not exist - FAIL" && exit 2
    if [ -n "$RUN_NOW" ]; then
        RUN_OK=""
        # Job is wanted to be run right now
        if [ -n "$AS_USER" ]; then
            # Run as user (find out correct user name)
            DEF_UID=$(grep "^UID_MIN" /etc/login.defs |  tr -s " " | cut -d " " -f2)
            DEVICEUSER=$(getent passwd $DEF_UID | sed 's/:.*//')
            [ -n "$DEVICEUSER" ] && su -l $DEVICEUSER /usr/lib/oneshot.d/$JOB && RUN_OK="1"
        else
            # run as root
            /usr/lib/oneshot.d/$JOB && RUN_OK="1"
        fi

        if [ -n "$RUN_OK" ]; then
            echo "add-oneshot: /usr/lib/oneshot.d/$JOB - run OK"
            shift && continue
        else
            echo "add-oneshot: /usr/lib/oneshot.d/$JOB - could not be run, save for later"
        fi
    fi

    # Either --now was not defined or our run failed
    # Create link so we run this job later
    LOCATION=0
    [ -n "$AS_USER" ] && LOCATION=default
    SAVE_OK=""
    ln -sf /usr/lib/oneshot.d/$JOB /etc/oneshot.d/$LOCATION && SAVE_OK="1"
    if [ -n "SAVE_OK" ]; then
        echo "add-oneshot: /etc/oneshot.d/$LOCATION/$JOB - job saved OK"
    else
        echo "add-oneshot: /etc/oneshot.d/$LOCATION/$JOB - job saving FAILED"
    fi
    shift
done
exit 0
