#!/bin/bash


ETHERPAD_LITE_USER=${ETHERPAD_LITE_USER:-etherpad}
ETHERPAD_LITE_GROUP=${ETHERPAD_LITE_GROUP:-etherpad}

set -eux # -x for verbose logging to juju debug-log

apt-get -y install git-core sqlite3 python-software-properties



sudo add-apt-repository -y ppa:chris-lea/node.js
sudo apt-get update
sudo apt-get install -y nodejs


mkdir /opt/apps -p

(
    cd /opt/apps &&
    git clone git://github.com/ether/etherpad-lite.git &&
    cd etherpad-lite &&
    adduser --system --home=/home/"$ETHERPAD_LITE_USER" --group "$ETHERPAD_LITE_GROUP" &&
    chown "$ETHERPAD_LITE_USER":"$ETHERPAD_LITE_GROUP" /opt/apps/etherpad-lite -R &&
    ## -H is to force HOME environment variable to change to etherpad one.
    sudo -u "$ETHERPAD_LITE_USER" -H bin/installDeps.sh
)

##
## Config file
##

config_file="/etc/etherpad-lite/settings.json"

[ -e "$config_file" ] || cp "src/etc/etherpad-lite/settings.json" "$config_file"

ln -sf "$config_file" /opt/apps/etherpad-lite/settings.json


##
## Storage
##

# is set from config file and by lxc-scripts as its declared as a data-dir


##
## Startup file
##

cp src/etc/init/etherpad-lite.conf /etc/init/etherpad-lite.conf

##
## Logrotate
##

cp src/etc/logrotate.d/etherpad-lite /etc/logrotate.d/etherpad-lite


##
## sqlite3 module
##

apt-get install -y build-essential
(
## XXXvlab: not very sure why you need to go in this directory
cd /opt/apps/etherpad-lite &&
sudo -u "$ETHERPAD_LITE_USER" -H npm install sqlite3
)
chown "$ETHERPAD_LITE_USER" /var/lib/etherpad-lite