#!/bin/sh
# Copyright (c) 2013 - 2020 Jolla Ltd.
# Copyright (c) 2020 Open Mobile Platform LLC.
#
# This adds oneshot job to be run durint preinit
# usage: add-oneshot <path-of-your-script> [<more paths>]
# Path has to point to existing executable file

[ -z "$1" ] && echo "add-preinit-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" ] || echo "$PATH" | grep -q sbin; then
    PATH="/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin"
fi

set +e

while [ -n "$1" ]; do
    JOB=$1
    # Job must exist and it must be executable
    [ ! -x $JOB ] && echo "add-preinit-oneshot: $JOB does not exist - FAIL" && exit 2
    # Create link so we run this job later in preinit
    SAVE_OK=""
    JOB_NAME=$(basename $JOB)
    ln -sf $JOB /etc/oneshot.d/preinit/$JOB_NAME && SAVE_OK="1"
    if [ -n "$SAVE_OK" ]; then
        echo "add-preinit-oneshot: /etc/oneshot.d/preinit/$JOB_NAME - job saved OK"
    else
        echo "add-preinit-oneshot: /etc/oneshot.d/preinit/$JOB_NAME - job saving FAILED"
    fi
    shift
done
exit 0
