#!/bin/bash

[ -f ~/app-root/data/.bash_profile ] && source ~/app-root/data/.bash_profile

source /etc/init.d/functions 2> /dev/null

# Support pre-Typeless cartridge variable names
function translate_env_vars {
  source_if_exists $OPENSHIFT_HOMEDIR/.env/TYPELESS_TRANSLATED_VARS
  xlations=( $(echo $TRANSLATE_GEAR_VARS) )
  i=0
  while [ "${xlations[$i]}" ]
  do
    keyname="${xlations[$i]}"
    i=$(( $i + 1 ))
    valref="${xlations[$i]}"
    i=$(( $i + 1 ))
    keyprev=$(eval "echo \$$keyname")
    if [ "$keyname" ] && [ "$valref" ] && [ -z "$keyprev" ]
    then
      eval "export ${keyname}=\"\$${valref}\""
    fi
  done
}

# source OpenShift environment variable into context
function load_env {
    [ -z "$1" ] && return 1
    [ -f "$1" ] || return 0

    local contents="$(< $1)"
    if [[ $contents =~ ^export\ .* || "$1" =~ .*USER_VARS$ ]]
    then
      source $1
    elif [[ "$1" =~ .*TYPELESS_TRANSLATED_VARS$ ]]
    then
      translate_env_vars
    else
      local key=$(basename $1)
      export $key="$(< $1)"
    fi
}

if [ -f ~/.env/CARTRIDGE_VERSION_2 ]
then
    for f in /etc/openshift/env/* ~/.env/* ~/.env/.uservars/* ~/*/env/*
    do
      load_env $f
    done

    if [ -n "$OPENSHIFT_PRIMARY_CARTRIDGE_DIR" ]
    then
        for f in $OPENSHIFT_PRIMARY_CARTRIDGE_DIR/env/*
        do
          load_env $f
        done
    fi

    path=$(env |grep 'OPENSHIFT_.*_PATH_ELEMENT'| sed 's/^.*=\(.*\)$/\1/'|tr '\n' ':')

    if [ -f $OPENSHIFT_PRIMARY_CARTRIDGE_DIR/env/OPENSHIFT_*_PATH_ELEMENT ]
    then
        path=$(< $OPENSHIFT_PRIMARY_CARTRIDGE_DIR/env/OPENSHIFT_*_PATH_ELEMENT):$path
    fi

    if [ -f /etc/openshift/env/PATH ]
    then
        load_env /etc/openshift/env/PATH
        path=$path:$PATH
    fi
    export PATH=$path
else
  for f in ~/.env/*
  do
    load_env $f
  done
fi

source /etc/openshift/node.conf

function welcome {
    cat 1>&2 <<EOF

    *********************************************************************

    You are accessing a service that is for use only by authorized users.  
    If you do not have authorization, discontinue use at once. 
    Any use of the services is subject to the applicable terms of the 
    agreement which can be found at: 
    https://www.openshift.com/legal

    *********************************************************************

    Welcome to OpenShift shell

    This shell will assist you in managing OpenShift applications.

    !!! IMPORTANT !!! IMPORTANT !!! IMPORTANT !!!
    Shell access is quite powerful and it is possible for you to
    accidentally damage your application.  Proceed with care!
    If worse comes to worst, destroy your application with 'rhc app delete'
    and recreate it
    !!! IMPORTANT !!! IMPORTANT !!! IMPORTANT !!!

    Type "help" for more info.

EOF

  if [ -f ~/.env/CARTRIDGE_VERSION_2 ]
  then
    cat 1>&2 <<EOF
    Note: Your application supports version 2 cartridges.

EOF
  fi

  # Quota returns nonzero if you are over limit
  quota >/dev/null 2>&1
  if [ $? -ne 0 ]
  then
      echo "Your application is out of disk space; please run \"rhc app-tidy $OPENSHIFT_APP_NAME\"" 1>&2
  fi
}

if [ -f ~/.env/CARTRIDGE_VERSION_2 ]
then
    alias ctl_app=gear

    function ctl_all() {
      case "$1" in
        start)
          echo "Starting services"
          gear start
        ;;
        stop)
          echo "Stopping services"
          gear stop
        ;;
        restart)
          echo "Stopping services"
          gear stop;
          echo "Starting services"
          gear start
        ;;
      esac
    }
else
    function _get_app_ctl_script() {
        bash <<EOF
            source /etc/openshift/node.conf
            source \${CARTRIDGE_BASE_PATH}/abstract/info/lib/util
            get_framework_ctl_script "$@"
EOF
    }

    alias ctl_app=$(_get_app_ctl_script $OPENSHIFT_GEAR_UUID)

    function ctl_all() {
        case "$1" in
            start)
              echo "Starting services"
              start_app.sh
              ;;
            stop)
              echo "Stopping services"
              stop_app.sh
              ;;
            restart)
              echo "Stopping services"
              stop_app.sh;
              echo "Starting services"
              start_app.sh
              ;;
        esac
    }
fi

function mysql() {
   #  Setup default options.
   [ -n "$OPENSHIFT_MYSQL_DB_HOST" ]  &&  hostopt="-h $OPENSHIFT_MYSQL_DB_HOST"
   portopt="-P ${OPENSHIFT_MYSQL_DB_PORT:-3306}"
   useropt="-u ${OPENSHIFT_MYSQL_DB_USERNAME:-'admin'}"
   passopt=--password="$OPENSHIFT_MYSQL_DB_PASSWORD"

   #  Unset default value if it was provided to us.
   for arg in $@; do
      case "$arg" in
         --host=*|-h)      unset hostopt  ;;
         --port=*|-P)      unset portopt  ;;
         --user=*|-u)      unset useropt  ;;
         --password=*|-p)  unset passopt  ;;
         *)  ;;
      esac
   done

   /usr/bin/mysql ${hostopt} ${portopt} ${useropt} ${passopt} "$@"

}  #  End of  mysql  function.

function psql() {
  pghost=${PGHOST:-$OPENSHIFT_POSTGRESQL_DB_HOST}
  pattern="^/"
  if [[ ! $pghost =~ $pattern ]]
  then
    pgport=${PGPORT:-$OPENSHIFT_POSTGRESQL_DB_PORT}
  fi
  pguser=${PGUSER:-$OPENSHIFT_POSTGRESQL_DB_USERNAME}
  pgpassword=${PGPASSWORD:-$OPENSHIFT_POSTGRESQL_DB_PASSWORD}
  pgdatabase=${PGDATABASE:-$OPENSHIFT_APP_NAME}

  extra_args=""
  # Ensure our psqlrc sets the histfile
  grep HISTFILE $HOME/.psqlrc &> /dev/null
  if [ $? -ne 0 ]
  then
    extra_args="${extra_args} --set HISTFILE=$OPENSHIFT_DATA_DIR/.psql_history-$pgdatabase"
  fi

  PGHOST=$pghost \
    PGPORT=$pgport \
    PGUSER=$pguser \
    PGPASSWORD=$pgpassword \
    PGDATABASE=$pgdatabase \
    /usr/bin/psql $extra_args "$@"
}

function mongo() {
   if test $# -gt 0; then
      uopt=""
      popt=""
   else
      uopt="--username ${OPENSHIFT_MONGODB_DB_USERNAME:-'admin'}"
      [ -n "$OPENSHIFT_MONGODB_DB_PASSWORD" ]  &&  popt="--password $OPENSHIFT_MONGODB_DB_PASSWORD"
   fi

   if echo "$@" | egrep "\-\-host|$OPENSHIFT_MONGODB_DB_HOST" > /dev/null; then
      hopt=""  #  Do not override if --host is passed.
   else
      if [ -n "$OPENSHIFT_MONGODB_DB_GEAR_DNS" ]; then
         hopt="${OPENSHIFT_MONGODB_DB_GEAR_DNS:-'127.0.0.1'}:${OPENSHIFT_MONGODB_DB_PORT:-27017}/admin"
      else
         hopt="${OPENSHIFT_MONGODB_DB_HOST:-'127.0.0.1'}:${OPENSHIFT_MONGODB_DB_PORT:-27017}/admin"
      fi
   fi

   ( unset LD_LIBRARY_PATH; /usr/bin/mongo ${hopt} ${uopt} ${popt} "$@" )

}  #  End of  mongo  function.

# The mco command shouldn't be run by gears
# but its really protected at the config files.
function mco {
    echo "mco: Permission denied" >&2
    return 255
}

# Add safety checks around rm to prevent 'rm -rf'
# from destroying the git repo.
function rm {
    end_args=""
    for test_arg in "$@"
    do
        if [ \( -n "$end_args" \) -o \( "${test_arg:0:1}" != "-" \) ]
        then
            for f in $(eval echo "$test_arg")
            do
                if [ -e "$f" ]
                then
                    if ! [ -O "$f" ]
                    then
                        echo "ERROR: Refusing unsafe deletion: $f" >&2
                        return 254
                    fi
                fi
            done
        elif [ "$test_arg" == "--" ]
        then
            end_args="1"
        fi
    done
    /usr/bin/env rm "$@"
}

function help {
    cat <<EOF
Help menu: The following commands are available to help control your openshift
application and environment.

ctl_app         control your application (start, stop, restart, etc)
ctl_all         control application and deps like mysql in one command
tail_all        tail all log files
export          list available environment variables
rm              remove files / directories
ls              list files / directories
ps              list running applications
kill            kill running applications
mysql           interactive MySQL shell
mongo           interactive MongoDB shell
psql            interactive PostgreSQL shell
quota           list disk usage

EOF

}

function tail_all {
    /usr/bin/tail -f */logs/*
}

export PS1="[$OPENSHIFT_GEAR_DNS \W]\> "
export TMOUT=300
export SHELL=/bin/bash
welcome

# Since the user is actively using this gear, unidle the gear (if idle).
which unidle_gear.sh &> /dev/null  &&  unidle_gear.sh "${PS1:+'show-messages'}"

if [ -z $SSH_TTY ]; then
    echo "WARNING: This ssh terminal was started without a tty." 1>&2
    echo "          It is highly recommended to login with: ssh -t" 1>&2
fi
