#!/bin/bash
#
#+ Swiss Army Knife
#|
#| Provides a fair amount of tools to work on various software
#| installations either one-by-one or en-masse.
#|
#| @link https://stash.endurance.com/projects/HGADMIN/repos/wptoolbox/browse GIT Repository
#| @author Jon South <jsouth@hostgator.com>
#| @package Bash
#- @subpackage Main

SAK_VER="0.1.5-PHP"
SAK_TS="20150616.A"

#+ Tests for proper versions of PHP or Python.
#| @param string $type Binary type.
#| @param string $path Binary path name.
#- @return bool True on test success. False otherwise.
sak_test_bin() {
  local type="$1" bin="$2"
  [[ ! -f "$bin" || ! -x "$bin" ]] && return 1
  case "$type" in
    python) opt=""; code="$(printf 'import sys\nif sys.version_info[:2]<(2,4):\n sys.exit(1)\nelse:\n print "success"')"  ;;
    php)    opt="-q"; code='<?php if(php_sapi_name()!="cli"||substr(PHP_VERSION,0,1)<5)exit(1);else echo "success\n";' ;;
    *) return 1 ;;
  esac
  [[ "$("$bin" $opt <<< "$code" 2>&1)" == "success" ]] &&
    printf '%s' "$bin" && return 0
  return 1
}

#+ Searches for PHP or Python.
#| @uses sak_test_bin
#| @param string $type Binary type.
#- @return string|bool Binary path name. False if not found or not acceptable.
sak_find_bin() {
  local type="$1" bin i=0 dirs=() bins=("php-cli" "php")
  [[ "$type" == "python" ]] && bins=("python")
  IFS=":" read -ra dirs <<< "$PATH" # Splits $PATH into a usable array
  for bin in "${bins[@]}"; do
    for dir in "${dirs[@]}"; do
      sak_test_bin "$type" "${dir%%/}/${bin}" && return 0
    done
  done
  return 1
}

#+ Die with an error.
sak_fatal() {
  printf "\n"
  printf "\e[37;1m[\e[31m!!\e[37m] %s\e[0m\n" "$@" >&2
  printf "\n"
  exit 1
}

# Store our full and base name for later usage where it needs to be printed
# Base defaults to "sak"
SAK_SELF="$0"
SAK_BASENAME="$(basename $0)"
if [[ "${0%%/$SAK_BASENAME}" == "/dev/fd" || "$SAK_BASENAME" == "stdin" || -z "$SAK_BASENAME" || "$SAK_BASENAME" == "-" ]]; then SAK_BASENAME="sak"; fi

SAK_SID_STRING="${SSH_CONNECTION-$PPID}${RUSER--}"

#+ Open and redirect FD3 to STDERR
#- @todo This may no longer be needed.
exec 3>&2

# Python >= 2.4 is required for VDetect
if [[ -z "$SAK_PYTHON" || ! -x "$SAK_PYTHON" ]]; then
  SAK_PYTHON="$(sak_find_bin "python")" ||
    sak_fatal "Unable to locate usable Python version 2.4 or higher." \
              "You may specify a custom Python binary with the SAK_PYTHON environment variable."
else
  sak_test_bin "python" "$SAK_PYTHON" >/dev/null ||
    sak_fatal "Usable Python 2.4 or higher was not found at '$SAK_PYTHON'."
fi

# Check for valid $SAK_PHP, find one if not
if [[ -z "$SAK_PHP" || ! -x "$SAK_PHP" ]]; then
  SAK_PHP="$(sak_find_bin "php")" ||
    sak_fatal "Unable to locate usable PHP version 5 or higher with the CLI SAPI." \
              "You may specify a custom PHP binary with the SAK_PHP environment variable."
else
  sak_test_bin "php" "$SAK_PHP" ||
    sak_fatal "Usable PHP CLI version 5 or higher was not found at '$SAK_PHP'."
fi

# Get default coloring for ls if not already set
if [[ -z "$LS_COLORS" ]] && which dircolors &>/dev/null; then
  . <(dircolors)
fi

SAK_DIR="/root/bin/.sak"
SAK_INCLUDES="$SAK_DIR:$SAK_DIR/lib"

PEAR="$(which pear 2>/dev/null)" &&
PEAR="${PEAR%/bin/pear}/lib"

# Setup PHP include directories
for DIR in "$PEAR" "/usr/local/lib/php" "/usr/lib/php"; do
  [[ -n "$DIR" && -d "$DIR" ]] && SAK_INCLUDES="$SAK_INCLUDES:$DIR"
done

# Set up the TTY for PHP to read single characters from STDIN
if which stty &>/dev/null; then
  stty -icanon
fi

# Toss our variables out where PHP can read them.
export SAK_VER SAK_TS SAK_SID_STRING SAK_PHP SAK_PYTHON SAK_DIR SAK_SELF \
       SAK_BASENAME RUSER LS_COLORS

# Based on PEAR
exec "$SAK_PHP" -H -C -q -d include_path="$SAK_INCLUDES" -d output_buffering=0 \
  -d date.timezone="America/Chicago" -d variables_order=EGPCS -d open_basedir="" \
  -d implicit_flush=1 -d safe_mode=0 -d register_argc_argv="On" \
  -d auto_prepend_file="" -d auto_append_file="" -d disable_functions="" \
  "$SAK_DIR/swiss-army-knife.php" "$@"
