#!/usr/bin/env bash

clear

temp_file=$(mktemp)

echo -e "** Testfile '$temp_file' (will be removed at end of script) **"
cat <<EOF > $temp_file
#! /usr/bin/env bash
#     Written by Miquel van Smoorenburg <miquels@cistron.nl>.
# ...

INIT_SCRIPT=/etc/init.d/test-service

### BEGIN INIT INFO
# Provides: postfwd
# ...
### END INIT INFO

PATH=/sbin:/bin:/usr/sbin:/usr/bin
NAME=postfwd
DAEMON=/usr/sbin/\${NAME}
PIDFILE=/var/run/\$NAME.pid
DESC=postfwd
EOF

echo ""
echo -e "\033[33m"
cat $temp_file
echo -e "\033[m"
echo ""
echo ""

trim() {
    local var="$*"
    var="${var#"${var%%[![:space:]]*}"}"   # remove leading whitespace characters
    var="${var%"${var##*[![:space:]]}"}"   # remove trailing whitespace characters
    echo -n "$var"
}

trim_double_quotes() {
    local var="$*"
    var="${var#"${var%%[!\"]*}"}"   # remove leading double quotes
    var="${var%"${var##*[!\"]}"}"   # remove trailing double quotes
    echo -n "$var"
}

trim_single_quotes() {
    local var="$*"
    var="${var#"${var%%[!\']*}"}"   # remove leading single quote
    var="${var%"${var##*[!\']}"}"   # remove trailing single quote
    echo -n "$var"
}

read_env_from_file() {

   _file="$*"

   while read _ENV _REST ; do

      _ENV="$(trim $_ENV)"

      if [[ "$_ENV" =~ .{2,}=.+ ]]; then
         _key="${_ENV%=*}"
         _val="${_ENV##*=}"

         [[ "$_key" = "PATH" ]] && continue


         # - Remove leading / trailling double quotes
         # -    _val="${_val%\"}"
         # -    _val="${_val#\"}"
         # -
         _val="$(trim_double_quotes $_val)"

         #  - Remove leading / trailling double quotes
         # -    _val="${_val%\'}"
         # -    _val="${_val#\'}"
         # -
         _val="$(trim_single_quotes $_val)"

         if [[ -n "$(trim $_key)" ]] && [[ -n "$(trim $_val)" ]] ; then
            export $_ENV
            #export $(eval echo $_ENV)
         fi
      fi

   done < "$_file"

}


echo -e "\t\033[32m---\033[m"
echo -e "\tRead environment variables from Testfile \033[1m$temp_file\033[m:"
echo -e "\t\033[32m---\033[m"
read_env_from_file $temp_file

echo ""
echo -e "\tINIT_SCRIPT: \033[32m$INIT_SCRIPT\033[m"
echo ""
echo -e "\t# PATH Variable should be ommitted. So your real env PATH should be printed out"
echo -e "\t#"
echo -e "\tPATH:        $PATH"
echo ""
echo -e "\tNAME:        \033[32m$NAME\033[m"
echo -e "\tDDAEMON:     \033[32m$DAEMON\033[m"
echo -e "\tPIDFILE:     \033[32m$PIDFILE\033[m"
echo -e "\tDESC:        \033[32m$DESC\033[m"
echo ""

echo ""
echo ""
echo -e "\t# Maybe you have to evaluate some variable.."
echo -e "\t#"
echo -e "\tDDAEMON:     \033[32m$(eval echo $DAEMON)\033[m"
echo -e "\tPIDFILE:     \033[32m$(eval echo $PIDFILE)\033[m"
echo ""


rm -f $temp_file
exit 0
