#!/bin/bash

# Creates a php instance

# Exit on any errors
set -e

function print_help {
    echo "Usage: $0 app-name namespace uuid git-url"

    echo "$0 $@" | logger -p local0.notice -t openshift_origin_php_configure
    exit 1
}

while getopts 'd' OPTION
do
    case $OPTION in
        d) set -x
        ;;
        ?) print_help
        ;;
    esac
done

[ $# -eq 4 -o $# -eq 3 ] || print_help

cartridge_type="php-5.3"
source "/etc/openshift/node.conf"
source ${CARTRIDGE_BASE_PATH}/abstract/info/lib/util

setup_configure "$1" $2 $3 $4
disable_cgroups

check_cartridge_dir_doesnt_exist

# Repo
if [ ! -d $git_url ]; then
	clone_external_git_repo $application $user_id $group_id $uuid $git_url
else
	clone_git_repo $application $user_id $group_id $uuid "php 5.3"
fi

#
# Create the core of the application
#
create_cartridge_instance_dir "$cartridge_type"
PHPCART_INSTANCE_DIR=$(get_cartridge_instance_dir "$cartridge_type")
pushd "$PHPCART_INSTANCE_DIR" > /dev/null
create_standard_app_dirs
mkdir conf conf.d logs sessions
mkdir -p phplib/pear/{docs,ext,php,cache,cfg,data,download,temp,tests,www}
ln -s /usr/lib64/httpd/modules modules
ln -s /etc/httpd/conf/magic conf/magic
sed -e "s,TEMPLATE_SET_ME_SESSION_SAVE_PATH,$PHPCART_INSTANCE_DIR/sessions/," \
    -e "s,TEMPLATE_SET_ME_UPLOAD_TMP_DIR,$PHPCART_INSTANCE_DIR/tmp/," $CART_CONF_DIR/php.ini > $PHPCART_INSTANCE_DIR/conf/php.ini
popd > /dev/null

#
# Find an open localhost IP
#
IP=`find_open_ip $uid $uuid`

$CART_INFO_DIR/bin/deploy_httpd_config.sh $application $uuid $IP

# Pear requires a special pearrc file, this is that file:
pear config-create "$PHPCART_INSTANCE_DIR"/phplib/pear/ "$APP_HOME"/.pearrc > /dev/null 2>&1
pear -c "$APP_HOME"/.pearrc config-set php_ini "$PHPCART_INSTANCE_DIR"/conf/php.ini > /dev/null 2>&1
pear -c "$APP_HOME"/.pearrc config-set auto_discover 1 > /dev/null 2>&1
observe_setup_var_lib_file "$APP_HOME"/.pearrc

populate_repo_dir

secure_app_dir

secure_cart_instance_dir

secure_conf_dirs

observe_setup_app_and_git_dirs

observe_setup_cart_instance_dir

#
# Create environment variables
#
create_standard_cart_env_vars
create_standard_env_uservars
create_standard_network_env_vars $IP
create_cart_network_env_vars $IP
create_standard_repo_dir_env_var
create_standard_path_env_var

observe_setup_env_uservars_dir


if [ ! -d $git_url ]; then
    #
    # Resolve app dependencies for template
    #
    resolve_application_dependencies $uuid $application &
else
    #
    # Start the server
    #
    start_app
fi

#
# Create virtualhost definition for apache
#
export CART_INFO_DIR
$CARTRIDGE_BASE_PATH/abstract/info/bin/deploy_httpd_proxy.sh $application $namespace $uuid $IP

restart_httpd_graceful
enable_cgroups
