#!/bin/bash -ex
#adopted from :
# http://www.theopensourcerer.com/2011/04/19/how-to-install-openerp-6-on-ubuntu-10-04-lts-server-part-1/
#Caution : please stop any instance of running postgres daemon


PSQLRELEASE=8.4
PYTHONRELEASE=python2.6
UBUNTURELEASE=10.04.1
SERVERSRC=openerp-server-6.0.3
WEBSRC=openerp-web-6.0.3
INSTALLPATH=/opt/openerp
PASSWVAR="openerp"
HOSTNAME=openerp

# set hostname
echo "$HOSTNAME" > /etc/hostname
sed -i "s|127.0.1.1 \(.*\)|127.0.1.1 $HOSTNAME|" /etc/hosts


echo "------------------------------------"
echo "Enabling ubuntu multiverse repository"
echo "------------------------------------"
APTSOURCES=/etc/apt/sources.list.d/sources.list

COMMENT=`grep 'lucid multiverse' $APTSOURCES`
UNCOMMENT=$(echo $COMMENT | sed 's|#||')
sed -i "s|$COMMENT|$UNCOMMENT|" $APTSOURCES

COMMENT=`grep 'lucid-updates multiverse' $APTSOURCES`
UNCOMMENT=$(echo $COMMENT | sed 's|#||')
UNCOMMENT=$(echo $COMMENT | sed 's|#||')
sed -i "s|$COMMENT|$UNCOMMENT|" $APTSOURCES

apt-get update
echo "------------------------------------"
echo "installing needed packages"
echo "------------------------------------"

apt-get -y install sudo python python-psycopg2 python-reportlab \
python-egenix-mxdatetime python-tz python-pychart python-mako \
python-pydot python-lxml python-vobject python-yaml python-dateutil \
python-pychart python-pydot python-webdav python-cherrypy3 \
python-formencode python-pybabel python-simplejson python-pyparsing

#Create openerp as system user
/usr/sbin/adduser --system --home=/opt/openerp --group openerp

#create pgsql user called openerp
#/etc/init.d/postgresql-$PSQLRELEASE stop

/etc/init.d/postgresql-$PSQLRELEASE start
sudo -u postgres createuser openerp --no-superuser --createdb --no-createrole
#Alter user open erp with defined password
sudo -u postgres psql template1 -U postgres -c "alter user openerp with password '$PASSWVAR'"

###-----Seting up OpenErp Server
#------Core OpenErp Server
cd /opt/openerp
wget http://www.openerp.com/download/stable/source/$SERVERSRC.tar.gz
wget http://www.openerp.com/download/stable/source/$WEBSRC.tar.gz
tar zxvf $SERVERSRC.tar.gz
tar zxvf $WEBSRC.tar.gz
rm -f  *.tar.gz
chown -R openerp: *
mv  $SERVERSRC server
mv $WEBSRC web

#-------Include US chart of accounts addon
wget http://apps.openerp.com/addon/get_module_as_zip/1067/l10n_chart_us_general.zip
unzip l10n_chart_us_general.zip
rm l10n_chart_us_general.zip
mv l10n_chart_us_general server/bin/addons
chown -R openerp: server/bin/addons/l10n_chart_us_general

#------Creating /etc/openerp-server.conf
cat > /tmp/openerp-server.conf <<"EOF"
[options]
; This is the password that allows database operations
; Will be written to by the server when password is changed
; !! Keep this file secure !!
; admin_passwd = admin

root_path = /opt/openerp/server/bin

without_demo = False
verbose = False

; Database settings
db_user = openerp
db_password = openerp
; Please uncomment the following line *after* you have created the
; database. It activates the auto module check on startup.
; db_name = False
db_port = False
db_host = False
db_maxconn = 64

; Networking Settings
xmlrpc = True
xmlrpc_interface =
xmlrpc_port = 8069

netrpc = True
netrpc_interface = 
netrpc_port = 8070

; Uncomment these for xml-rpc over SSL
;xmlrpcs = True
;xmlrpcs_interface =
;xmlrpcs_port = 8071
;secure_pkey_file = /etc/ssl/openerp/server.pkey
;secure_cert_file = /etc/ssl/openerp/server.crt

; Log settings
logfile = /var/log/openerp/openerp-server.log
syslog = False
logrotate = True
log_level = info

; False prevents the client displaying the list of databases
list_db = True
addons_path = /opt/openerp/server/bin/addons
demo = {}
soap = False
reportgz = False
translate_modules = ['all']

; Static http parameters
static_http_enable = False
static_http_document_root = /var/www/html
static_http_url_prefix = /

; Outbound email configuration
;smtp_user = info@example.com
;email_from = "OpenERP Support" <info@example.com>
;smtp_port = 25
;smtp_password = ********
;smtp_ssl = True
;smtp_server = mail.example.com
EOF

mv /tmp/openerp-server.conf /etc/openerp-server.conf
chown openerp:root /etc/openerp-server.conf
chmod 640 /etc/openerp-server.conf

#------End creating /etc/openerp-server.conf

#------Creating init.d script
cat > /tmp/openerp-server <<"EOF"
#!/bin/sh

### BEGIN INIT INFO
# Provides:             openerp-server
# Required-Start:       $remote_fs $syslog
# Required-Stop:        $remote_fs $syslog
# Should-Start:         $network
# Should-Stop:          $network
# Default-Start:        2 3 4 5
# Default-Stop:         0 1 6
# Short-Description:    Enterprise Resource Management software
# Description:          Open ERP is a complete ERP and CRM software.
### END INIT INFO

PATH=/bin:/sbin:/usr/bin
DAEMON=/opt/openerp/server/bin/openerp-server.py
NAME=openerp-server
DESC=openerp-server

# Specify the user name (Default: openerp).
USER=openerp

# Specify an alternate config file (Default: /etc/openerp-server.conf).
CONFIGFILE="/etc/openerp-server.conf"

# pidfile
PIDFILE=/var/run/$NAME.pid

# Additional options that are passed to the Daemon.
DAEMON_OPTS="-c $CONFIGFILE"

[ -x $DAEMON ] || exit 0
[ -f $CONFIGFILE ] || exit 0

checkpid() {
    [ -f $PIDFILE ] || return 1
    pid=`cat $PIDFILE`
    [ -d /proc/$pid ] && return 0
    return 1
}

case "${1}" in
        start)
                echo -n "Starting ${DESC}: "

                start-stop-daemon --start --quiet --pidfile ${PIDFILE} \
                        --chuid ${USER} --background --make-pidfile \
                        --exec ${DAEMON} -- ${DAEMON_OPTS}

                echo "${NAME}."
                ;;

        stop)
                echo -n "Stopping ${DESC}: "

                start-stop-daemon --stop --quiet --pidfile ${PIDFILE} \
                        --oknodo

                echo "${NAME}."
                ;;

        restart|force-reload)
                echo -n "Restarting ${DESC}: "

                start-stop-daemon --stop --quiet --pidfile ${PIDFILE} \
                        --oknodo
      
                sleep 1

                start-stop-daemon --start --quiet --pidfile ${PIDFILE} \
                        --chuid ${USER} --background --make-pidfile \
                        --exec ${DAEMON} -- ${DAEMON_OPTS}

                echo "${NAME}."
                ;;

        *)
                N=/etc/init.d/${NAME}
                echo "Usage: ${NAME} {start|stop|restart|force-reload}" >&2
                exit 1
                ;;
esac

exit 0
EOF

mv /tmp/openerp-server /etc/init.d/
chmod 755 /etc/init.d/openerp-server
chown root: /etc/init.d/openerp-server
update-rc.d openerp-server defaults
#---------End creating init.d script


#Create /var/log/openerp with proper ownership:
mkdir -p /var/log/openerp
chown -R openerp.root /var/log/openerp/



###--------Setting up openerp  web client
#------Creating /etc/openerp-web.conf
cat > /tmp/openerp-web.conf <<"EOF"
[global]
server.environment = "development"

# Some server parameters that you may want to tweak
server.socket_host = "0.0.0.0"
server.socket_port = 8080

# Sets the number of threads the server uses
server.thread_pool = 10

tools.sessions.on = True
tools.sessions.persistent = False

# Simple code profiling
server.profile_on = False
server.profile_dir = "profile"

# if this is part of a larger site, you can set the path
# to the TurboGears instance here
#server.webpath = ""

# Set to True if you are deploying your App behind a proxy
# e.g. Apache using mod_proxy
#tools.proxy.on = True

# If your proxy does not add the X-Forwarded-Host header, set
# the following to the *public* host url.
#tools.proxy.base = 'http://mydomain.com'

# logging
#log.access_file = "/var/log/openerp-web/access.log"
log.error_file = "/var/log/openerp/openerp-web-error.log"
log.access_level = "INFO"
log.error_level = "INFO"

# Set to false to disable CSRF checks
tools.csrf.on = True

# replace builtin traceback tools by cgitb
tools.log_tracebacks.on: False
tools.cgitb.on: True
# a default install can probably avoid logging those via cgitb as they're
# available in the server log
tools.cgitb.ignore=(
    openobject.errors.Concurrency,
    openobject.errors.TinyException)

# OpenERP Server
openerp.server.host = 'localhost'
openerp.server.port = '8070'
openerp.server.protocol = 'socket'
openerp.server.timeout = 450

# Web client settings
[openerp-web]
# filter dblists based on url pattern?
# NONE: No Filter
# EXACT: Exact Hostname
# UNDERSCORE: Hostname_
# BOTH: Exact Hostname or Hostname_

dblist.filter = 'NONE'

# whether to show Databases button on Login screen or not
dbbutton.visible = True

# will be applied on company logo
company.url = ''
EOF

mv /tmp/openerp-web.conf /etc/
chown openerp:root /etc/openerp-web.conf
sudo chmod 640 /etc/openerp-web.conf

#--------End creating /etc/openerp-web.conf

#------Creating /etc/init.d/openerp-web
cat > /tmp/openerp-web <<"EOF"
#!/bin/sh

### BEGIN INIT INFO
# Provides:             openerp-web
# Required-Start:       $remote_fs $syslog
# Required-Stop:        $remote_fs $syslog
# Should-Start:         $network
# Should-Stop:          $network
# Default-Start:        2 3 4 5
# Default-Stop:         0 1 6
# Short-Description:    OpenERP Web - the Web Client of the OpenERP
# Description:          Open ERP is a complete ERP and CRM software.
### END INIT INFO

PATH="/sbin:/bin:/usr/sbin:/usr/bin"
DAEMON="/opt/openerp/web/openerp-web.py"
NAME="openerp-web"
DESC="openerp-web"

# Specify the user name (Default: openerp).
USER=openerp

# Specify an alternate config file (Default: /etc/openerp-web.conf).
CONFIGFILE="/etc/openerp-web.conf"

# pidfile
PIDFILE=/var/run/$NAME.pid

# Additional options that are passed to the Daemon.
DAEMON_OPTS="-c $CONFIGFILE"

[ -x $DAEMON ] || exit 0
[ -f $CONFIGFILE ] || exit 0

checkpid() {
    [ -f $PIDFILE ] || return 1
    pid=`cat $PIDFILE`
    [ -d /proc/$pid ] && return 0
    return 1
}

case "${1}" in
        start)
                echo -n "Starting ${DESC}: "

                start-stop-daemon --start --quiet --pidfile ${PIDFILE} \
                        --chuid ${USER} --background --make-pidfile \
                        --exec ${DAEMON} -- ${DAEMON_OPTS}

                echo "${NAME}."
                ;;

        stop)
                echo -n "Stopping ${DESC}: "

                start-stop-daemon --stop --quiet --pidfile ${PIDFILE} \
                        --oknodo

                echo "${NAME}."
                ;;

        restart|force-reload)
                echo -n "Restarting ${DESC}: "

                start-stop-daemon --stop --quiet --pidfile ${PIDFILE} \
                        --oknodo

                sleep 1

                start-stop-daemon --start --quiet --pidfile ${PIDFILE} \
                        --chuid ${USER} --background --make-pidfile \
                        --exec ${DAEMON} -- ${DAEMON_OPTS}

                echo "${NAME}."
                ;;

        *)
                N=/etc/init.d/${NAME}
                echo "Usage: ${NAME} {start|stop|restart|force-reload}" >&2
                exit 1
                ;;
esac

exit 0
EOF

mv /tmp/openerp-web /etc/init.d/
chmod 755 /etc/init.d/openerp-web
chown root: /etc/init.d/openerp-web
update-rc.d openerp-web defaults

#--------End creating /etc/init.d/openerp-web


apt-get clean
cd /opt

#add services information
SERVICES=/etc/confconsole/services.txt
echo 'Openerp:    http://$ipaddr:8080' >> $SERVICES

exit 0
