#!/bin/sh
cmd=`basename $0`

CWD=`pwd`
SCRIPTDIR=/opt/metasploit-framework/bin
cd $SCRIPTDIR
EMBEDDED=$SCRIPTDIR/../embedded
BIN=$EMBEDDED/bin
FRAMEWORK=$EMBEDDED/framework

LOCALCONF=~/.msf4
DB=$LOCALCONF/db
DBCONF=$LOCALCONF/database.yml
cd "$CWD"

add_path() {
  PROFILE=~/.profile
  if [ -e ~/.bash_profile ]; then
    PROFILE=~/.bash_profile
  fi
  echo "PATH=\$PATH:$SCRIPTDIR" >> $PROFILE
  echo "export PATH=\$PATH:$SCRIPTDIR" >> $PROFILE
  echo "You may need to start a new terminal or log in again for this to take effect."
}

check_db() {
  if [ ! -e $LOCALCONF/database.yml ]; then
    while read -p "Would you like to use and setup a new database (recommended)? " yn; do
      case $yn in
        [Yy]* ) $SCRIPTDIR/msfdb init; break;;
        [Nn]* ) break;;
            * ) echo "Please answer yes or no.";;
      esac
    done
  fi
}

check_path() {
  if ! hash $cmd 2>/dev/null; then
    while read -p "Would you like to add $cmd and other programs to your default PATH? " yn; do
      case $yn in
        [Yy]* ) add_path; break;;
        [Nn]* ) break;;
            * ) echo "Please answer yes or no.";;
      esac
    done
  fi
}

start_db() {
  if [ -e $DB -a -e $DBCONF ]; then
    if ! $BIN/pg_ctl -D $DB status > /dev/null; then
      $SCRIPTDIR/msfdb init
      sleep 2
    fi
  fi
}

init() {
  if [ ! -e $LOCALCONF/initial_setup_complete ]; then
    mkdir -p $LOCALCONF
    echo
    echo " ** Welcome to Metasploit Framework Initial Setup **"
    echo "    Please answer a few questions to get started."
    echo
    check_path
    echo
    check_db
    echo
    echo " ** Metasploit Framework Initial Setup Complete **"
    echo
    touch $LOCALCONF/initial_setup_complete
  fi

  start_db
}

# If we are on an updated Kali system, try to use the system database
db_args=""
if [ -e /usr/share/metasploit-framework/config/database.yml \
     -a ! -e $LOCALCONF/database.yml ]; then
  db_args="-y /usr/share/metasploit-framework/config/database.yml"
else # Skip initialization if we're root
  if [ "`id -u`" -gt 0 ]; then
    init
  fi
fi

unset GEM_HOME
unset GEM_PATH
unset GEM_ROOT
unset RUBY_ENGINE
unset RUBY_ROOT
PATH=$BIN:$SCRIPTDIR:$PATH
if [ -e "$FRAMEWORK/$cmd" ]; then

  if [ $cmd = "msfconsole" ]; then
    if [ -n "`find $FRAMEWORK/$cmd -mmin +20160`" ]; then
      (>&2 echo "This copy of metasploit-framework is more than two weeks old.")
      (>&2 echo " Consider running 'msfupdate' to update to the latest version.")
    fi
#   Uncomment to enable libedit support
#   cmd="$cmd -L"
    cmd="$cmd $db_args"
  fi

  exec $BIN/ruby $FRAMEWORK/$cmd "$@"
else
  if [ "$FROM_CONSOLE_PATH" = true ]; then
    (cd $FRAMEWORK && $BIN/ruby $BIN/$cmd "$@")
  else
    exec $BIN/ruby $BIN/$cmd "$@"
  fi
fi
