#!/bin/sh
# Copyright (c) 2012 - 2020 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" ] || echo "$PATH" | grep -q 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 "$UID" ] && export UID=$(id -u)
[ -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
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
