#!/bin/bash

# go to home dir
cd ~
wget http://pear.php.net/go-pear.phar
php5 go-pear.phar
rm go-pear.phar

# add include_path var and set it to /home/username/pear/share/pear
PHP_DIR=`pear/bin/pear config-get php_dir`
echo "As you didn't run this script as root the Chiara_PEAR_Server installer probably"
echo "can't overwrite your php.ini file. We're going to fix this by starting up nano"
echo "ourselves and edit the php.ini file"
echo "Find the include path setting and change it so that ${PHP_DIR} is present.";
echo "What is the location of your php.ini file? [/etc/php5/cli/php.ini]";
read PHP_INI
if [ -z "$PHP_INI" ]
then
   PHP_INI="/etc/php5/cli/php.ini"
fi
echo "Use Ctrl-W to find include_path (Ctrl-W <ENTER> searches again) and when"
echo "you are ready editing the php.ini file hit Ctrl-X, Y, <Enter> to save"
echo "the file"
echo "Press <Enter> to continue"
read
sudo nano $PHP_INI

if [ -e "/usr/bin/pear" ]
then
    echo "The pear binary is already present in /usr/bin/pear"
    echo "Perhaps you already installed php-pear?"
    echo "Do you want to replace this file with a symbolic link to"
    echo "the newly installed pear binary? [Yn]"
    read ANSWER
    if [ "$ANSWER" = "Y" ] || [ "$ANSWER" = "" ]
    then
        sudo rm /usr/bin/pear
        PEAR_BIN=`pear/bin/pear config-get bin_dir` 
        sudo ln -s $PEAR_BIN/pear /usr/bin/pear
    fi
fi
 
pear clear-cache
pear upgrade PEAR
pear channel-discover pear.chiaraquartet.net

echo "Make sure you have a database and a database user ready"
echo "If you haven't, here's some SQL to create one:"
echo ""
echo "CREATE USER 'pear'@'%' IDENTIFIED BY 'pear';"
echo "GRANT USAGE ON * . * TO 'pear'@'%' IDENTIFIED BY 'pear' WITH "
echo "MAX_QUERIES_PER_HOUR 0 MAX_CONNECTIONS_PER_HOUR 0 "
echo "MAX_UPDATES_PER_HOUR 0 MAX_USER_CONNECTIONS 0 ;"
echo "CREATE DATABASE 'pear' ;"
echo "GRANT ALL PRIVILEGES ON 'pear'.* TO 'pear'@'%';"
echo ""
echo "Press <Enter> to continue"
read

pear install --alldeps Chiara/Chiara_PEAR_Server-alpha

echo "What's the name of the database user? [pear]"
read DB_USER

if [ -z "$DB_USER" ]
then
    DB_USER="pear"
fi

echo "What's the name of the database? [pear]"
read DB

if [ -z "$DB" ]
then
    DB="pear"
fi

echo "Importing mysql data..."
DATA_DIR=`pear config-get data_dir`
mysql --user=$DB_USER -p --database=$DB < $DATA_DIR/Chiara_PEAR_Server/data/pearserver.sql
echo "Press <Enter> to continue"
read

pear run-scripts Chiara/Chiara_PEAR_Server


