#!/bin/sh
# Copyright (c) 2012 - 2019 Jolla Ltd.
# Copyright (c) 2019 - 2020 Open Mobile Platform LLC.
#
# Run all oneshot scripts indicated by links and after
# successful run remove the link

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

[ -z "$USER" ] && export USER=`id -u -n`
[ -z "$GROUP" ] && export GROUP=`id -g -n`

SUBDIR=""
[ "$1" == "--late" ] && SUBDIR=${SUBDIR}late/
[ "$GROUP" == "privileged" ] && SUBDIR=${SUBDIR}privileged/

if [ "$1" == "--mic" ]; then
    [ -f "/.bootstrap" ] && echo "/.bootstrap exists while running in mic-mode, which is probably not what you want"
    export MIC_RUN=1
    if [ $UID -eq 0 ]; then
        mkdir -p /var/run/dbus
        dbus-daemon --system
    else
        export DBUS_SESSION_BUS_ADDRESS=$(dbus-daemon --print-address --session --fork)
    fi
fi

set +e
LINKS=$(find /etc/oneshot.d/$UID/$SUBDIR -maxdepth 1 -type l | sort)
for SCRIPTLET in $LINKS; do
    if [ -e $SCRIPTLET ]; then
        $SCRIPTLET && rm $SCRIPTLET && echo "oneshot: $SCRIPTLET - OK" || echo "oneshot: $SCRIPTLET - FAIL"
    else
        rm $SCRIPTLET && echo "oneshot: '$SCRIPTLET' pointed to non-existent file. Removing link." || echo "oneshot: failed to remove $SCRIPTLET"
    fi
done
exit 0
