#!/bin/bash

# Exit on any error. More complex stuff could be done in future
# (see https://stackoverflow.com/questions/4381618/exit-a-script-on-error)
set -e

if [ "x$SAFE_MODE" == "xTrue" ]; then

    echo ""
    echo "[INFO] Not executing entrypoint as we are in safe mode, just opening a Bash shell."
    exec /bin/bash

else
    echo ""
    echo "[INFO] Executing entrypoint..."
    #---------------------
    #   Setup home
    #---------------------
     
    if [ ! -f "/home/metauser/.initialized" ]; then
        echo "[INFO] Setting up home"
        [ ! -d "/home/metauser" ] &&  mkdir -p /home/metauser
        # Copy over vanilla home contents
        if [ "x$DEBUG" == "xTrue" ] ; then
          ls -la /home/metauser
          ls -la /metauser_home_vanilla/
        fi 
        for x in /metauser_home_vanilla/* /metauser_home_vanilla/.[!.]* /metauser_home_vanilla/..?*; do
            if [ -e "$x" ]; then cp -a "$x" /home/metauser/; fi
        done
        if [ "x$DEBUG" == "xTrue" ] ; then
          ls -la /home/metauser
        fi
        # Mark as initialized
        [ ! -f "/home/metauser/.initialized" ] && touch /home/metauser/.initialized
    fi

    #---------------------
    #   Save env
    #---------------------
    echo "[INFO] Dumping env"

    # Save env vars for later usage (e.g. ssh)

    env | \
    while read env_var; do
      if [[ $env_var == HOME\=* ]]; then
          : # Skip HOME var
      elif [[ $env_var == PWD\=* ]]; then
          : # Skip PWD var
      else
          echo "export $env_var" >> /tmp/env.sh
      fi
    done


    echo "[INFO] Moving to /home/metauser and setting as home"
    cd /home/metauser
    export HOME=/home/metauser

    echo "[INFO] Setting new prompt @$CONTAINER_NAME container"
    echo 'export PS1="${debian_chroot:+($debian_chroot)}\u@$CONTAINER_NAME@\h:\w\$ "' >> /home/metauser/.bash_profile
    source /home/metauser/.bash_profile

    # Set entrypoint command
     if [ "x$@" == "x" ]; then
        # Start!
            echo -n "[INFO] Will execute entrypoint command: "
            echo ""
            echo "=============================================================="
            echo ""
            echo "      Welcome to the EUROEXA $CONTAINER_NAME container!"
            echo ""
            echo "=============================================================="
            echo ""
            echo "You are now in /home/skauser with write access as user \"$(whoami)\"."
            echo ""
            echo "Remember that contents inside this container, unless stored"
            echo "on a persistent volume mounted from you host machine, will"
            echo "be wiped out when exiting the container."
            echo ""
            COMMAND="/bin/bash"
        else
            COMMAND="$@"
        fi
fi
exec $COMMAND
