#!/bin/bash
export LC_ALL=C TERM="xterm"

trap 'shutdown_runit_services' INT TERM

# variables
env > /etc/envvars
temp_var=$@
FILES=/etc/container_environment/*
runsvdir_PID=

# functions

# importing the environment variables from image
import_envvars () {

 clear_existing_environment=${1:-true}
 override_existing_environment=${2:-true}

 for file in $FILES
 do
    FILE=`basename $file`
    if [ $override_existing_environment = true ] || !( env | grep -q $FILE)
    then
      export eval $FILE=`cat $file`
    fi
 done
}

# exporting the environment variables to the image
export_envvars () {
 to_dir=${1:-true}
 no_record="HOME USER GROUP UID GID SHELL SHLVL PWD"
 # to begin .json and.sh files
  echo -n "{" > /etc/container_environment.json
  echo -n "" > /etc/container_environment.sh
  # saving variables into file. individual file by variable.
 env | while read -r line
 do
  a=`expr index "$line" \=`
  b=$((a-1))
  file_name=${line:0:$b}
  file_val=${line:$a}
  if echo "$no_record" | grep -q "$file_name"
  then
   continue
  else
    # write to files
    if [ $to_dir = true ] ; then echo $file_val > /etc/container_environment/$file_name ; fi
   # write to .sh file
    echo "export"  $file_name"='"$file_val"'" >> /etc/container_environment.sh
   # write to .json file
    echo -n "\""$file_name"\":\""$file_val"\"," >> /etc/container_environment.json
  fi
 done
    # adding } to closed the .json file
    echo -e "\b}" >> /etc/container_environment.json
}

# function to run the command
run_command () {
   if [ -x $1 ]; then
        echo >&2 "*** Running: $1"
        $1
        retval=$?
        if [ $retval != 0 ];
        then
            echo >&2 "*** Failed with return value: $retval"
            exit $retval
         else
            import_envvars
            export_envvars false
        fi
    fi
}

# function to run the startup scripts
run_startup_files() {
   # running /etc/my_init.d/
   echo "Starting pre-service scritps in /etc/my_init.d"
   for script in /etc/my_init.d/*
    do
     run_command $script
   done

   echo "starting rc.local scritps"
   run_command /etc/rc.local
}


# function to start cron jobs
start_runit () {
   echo "Booting runit daemon..."
   /usr/bin/runsvdir -P /etc/service 'log:.........................................................................................................' &
   runsvdir_PID=$!
   echo "Process runsvdir running with PID $runsvdir_PID"
}

# function to shutdown corn jobs
shutdown_runit_services() {
   # need to check if runit service is runnung before shutdown ..
   echo "Begin shutting down runit services..."
   /usr/bin/sv down /etc/service/*
   # need to give some time and check if service is down if time greater than allow them force exit
   count=1
   while [ $(/usr/bin/sv status /etc/service/* | grep -c "^run:") != 0 ]
   do
     sleep 1
     count=`expr $count + 1`
     if [ $count -gt 10 ]; then break ; fi
   done
   exit 0
}

# message to echo things to user
message () {
  echo "usage: my_init [-h|--help] [--skip-startup-files] [--skip-runit] [-- MAIN_COMMAND ]"
  echo "optional arguments:"
  echo "  -h, --help            show this help message and exit"
  echo "  --skip-startup-files  Skip running /etc/my_init.d/* and /etc/rc.local"
  echo "  --skip-runit          Do not run runit services"
  echo "  --quiet               Only print warnings and errors"
}

# import & export env
import_envvars false false
export_envvars


# condition for --help
if [ `echo $temp_var | grep -c "\-\-help" ` -gt 0 ] || [ `echo $temp_var | grep -c "\-h" ` -gt 0 ] ; then
  message
  exit 0
fi

# condition for --quiet
if ! [ `echo $temp_var | grep -c "\-\-quiet" ` -gt 0 ] ; then
   :
 else
   temp_var=$(echo $temp_var|sed "s/--quiet//")
   echo "--quiet still need to be implememted"
fi

# condition for --skip-startup-files
if ! [ `echo $temp_var | grep -c "\-\-skip-startup-files" ` -gt 0 ] ; then
   run_startup_files
 else
   temp_var=$(echo $temp_var|sed "s/--skip-startup-files//")
fi

# condition for --skip-runit
if ! [ `echo $temp_var | grep -c "\-\-skip-runit" ` -gt 0 ] ; then
   start_runit
 else
   temp_var=$(echo $temp_var|sed "s/--skip-runit//")
   if  [ `echo $temp_var | grep -c "\-\- " ` -gt 0 ] ; then
     temp_var=$(echo $temp_var|sed "s/--//")
     exec $temp_var
     exit 0
    else
      echo "Need to add command to do something:  -- command"
      echo
      message
      exit 0
   fi
fi

if  [ `echo $temp_var | grep -c "\-\- " ` -gt 0 ] ; then
temp_var=$(echo $temp_var|sed "s/--//")
 if ! [ "$temp_var" = "" ] ; then
     # need to check if all service are online before executing command
     count=1
     while [ $(/sbin/sv status /etc/service/* | grep -c "^down:") != 0 ]
      do
       sleep 1
       count=`expr $count + 1`
       if [ $count -gt 10 ]; then break ; fi
      done
     exec $temp_var
     shutdown_runit_services
 else
  echo "Need to add command to do something: -- command "
  echo
  message
  shutdown_runit_services
 fi
fi

wait
