#!/bin/bash
#
# postplug - Postplug boot time configuration script
# Copyright (c) 2004-2017 by Silvan Calarco <silvan.calarco@mambasoft.it>
# Copyright (c) 2004-2007 by Davide Madrisan <davide.madrisan@qilinux.it>

if [ $UID != 0 ]; then
   echo "$0: must be superuser." >&2
   exit 1
fi

me="${0##*/}"

[ -r /etc/postplug/postplug.defs ] ||
 { currtime="`LANG=C date +\"%b %d %H:%M:%S\" 2>/dev/null`"
   echo "\
$currtime postplug: "$"error: "$"cannot read postplug.defs" >&2
   exit 1; }

. /etc/postplug/postplug.defs

[ -r /etc/sysconfig/i18n ] && . /etc/sysconfig/i18n

export LANG
export LC_ALL=$LANG
export POSTPLUGON=1

# set homedir if not set (needed at boot time execution)
[ "$HOME" ] || export HOME=/root

logmsg "" $"starting"" ${me}"

rm -f $postplugnewdir/*

# check via /proc/cmdline for plugins that must not be executed
# NOTE: /proc/cmdline sintaxes:
#    postplug=off : do not execute any plugins
#    postplug=noxorg,nosound : skip these two plugins

fin=/proc/cmdline
unset proc_pp_cmdline
if grep -qi "postplug=[a-zA-Z0-9]" $fin; then
   proc_pp_cmdline=$(cat $fin | sed 's/.*postplug=\([^ ]*\).*/\1/')
fi

function plugin_chkexec() {
   OIFS="$IFS"; IFS=','
   for token in $proc_pp_cmdline; do
      [ "${token}" = "no${1:2}" -o "${token}" = "off" ] &&
       { IFS="$OIFS"; return 0; }
   done
   IFS="$OIFS"
   return 1
}

# evaluate valid vars and export them for plugins
OIFS="$IFS"; IFS=','
for token in $proc_pp_cmdline; do
   case ${token} in
      freevideo|autoresvideo|lowresvideo) eval export ${token}=1 ;;
   esac
done
IFS="$OIFS"

for plugin in $(find /etc/postplug/rcpostplug.d/* 2>/dev/null | sort); do
   # get the plugin basename
   plugin_bn="${plugin##*/}"

   # check if the current plugin execution has been disabled
   plugin_chkexec "${plugin_bn}"

   if [ $? -eq 1 ]; then
      logmsg "${plugin_bn:2}" $"executing plugin"
      $plugin || {
         retval=$?
         logmsg "\
${plugin_bn:2}" $"error: "$"execution failed"" ($retval)"; }
   fi

done

rm -f $postpluglibdir/firsttime

exit 0
