#!/bin/sh

# this script should not fail: executed from statefs prestart it
#
# should execute 'once*' scripts from the 'once' dir where calling
# symlink is located and unlink it on success

my_link=$0
if ! [ -L $my_link ]; then
    echo "Should be run only by means of symlink"
    exit 0
fi

config_root=$(dirname $0)
scripts_dir=$config_root/once

if ! [ -d "$scripts_dir" ]; then
    echo "No scripts dir: $scripts_dir"
    echo "Expected ./once relative to $my_link"
    exit 0
fi

res=0

function exec_once {
    cmd=$1
    sh $cmd
    if [ $? -eq 0 ]; then
        echo "Ok: $cmd"
        rm $cmd
    else
        echo "No success with $cmd"
        export res=1
    fi
}

files=$(find $scripts_dir -type f -name 'once*')
for f in $files; do
    exec_once $f
done

if [ $res -eq 0 ]; then
    echo "Successfully executed, I can go away"
    unlink $my_link;
else
    echo "Maybe next time..."
fi

# to be sure it exits with 0
exit 0
