
## =================================================
## - Install etherpad-lite


## - il-pad.oopen.de
## -
#_node_version="0.10.26"
_node_version="0.10.32"
_source_base_dir="/usr/local/src"

_etherpad_instance=etherpad-lite
_etherpad_dir="/var/www/$_etherpad_instance"

_etherpad_user="etherpad"
_etherpad_group="etherpad"

#_etherpad_db_name="etherpad"
#_etherpad_db_user="etherpad"
#_etherpad_db_pass="HtfrxP9sfJqwRKrM"
_etherpad_db_name="il_pad"
_etherpad_db_user="il_pad"
_etherpad_db_pass="RPlJ3cTjTKs93N6H"

mysql_credential_args="--login-path=local_root"

_hostname="il-pad.oopen.de"
_ipv4="83.223.85.227"
_ipv6="2a01:30:1fff:5::227"

_etherpad_port="9001"
_etherpad_host="127.0.0.1"

_etherpad_admin="admin@oopen.de"
## -
## - End: il-pad.oopen.de


## - etherpad.oopen.de
## -
_node_version="0.10.28"
_source_base_dir="/usr/local/src"

_etherpad_instance=etherpad-lite
_etherpad_dir="/var/www/$_etherpad_instance"

_etherpad_user="etherpad"
_etherpad_group="etherpad"

_etherpad_db_name="etherpad"
_etherpad_db_user="etherpad"
_etherpad_db_pass="px3zPdsKMKzvXc3r"

mysql_credential_args="--login-path=local"

_hostname="etherpad.oopen.de"
_ipv4="83.223.85.45"
_ipv6="2a01:30:1fff:fe00::45"

_etherpad_port="9001"
_etherpad_host="127.0.0.1"

_etherpad_admin="admin-il-pad@oopen.de"
## -
## - End: etherpad.oopen.de


## - etherpad-ak.oopen.de
## -
_node_version="0.10.28"
_source_base_dir="/usr/local/src"

_etherpad_instance=etherpad-ak
_etherpad_dir="/var/www/$_etherpad_instance"

_etherpad_user="etherpad"
_etherpad_group="etherpad"

_etherpad_db_name="etherpad_ak"
_etherpad_db_user="etherpad_ak"
_etherpad_db_pass="NvLKX3Nt4kfCbjJw"

mysql_credential_args="--login-path=local"

_hostname="etherpad-ak.oopen.de"
_ipv4="83.223.85.45"
_ipv6="2a01:30:1fff:fe00::45"

_etherpad_port="9003"
_etherpad_host="127.0.0.1"

_etherpad_admin="admin@oopen.de"
## -
## - End: etherpad.oopen.de




## -------------------------------------------------
## - Install prerequisites

## - node
apt-get install libc6-dev libssl-dev make gcc g++
apt-get install gzip git-core curl python pkg-config build-essential
apt-get install libpq-dev postgresql-client

# - etherpad-lite
apt-get install abiword


## -------------------------------------------------
## - Install nginx

## - Installed from debian ports


## -------------------------------------------------
## - Install MySQL

## - MySQL is installed from source:
## -
## -    installdir = /usr/local/mysql
## -



## -------------------------------------------------
## - Install node (node.js)


mkdir -p  ${_source_base_dir}/node
cd ${_source_base_dir}/node

## - Download from project side http://nodejs.org/
## -
wget http://nodejs.org/dist/v${_node_version}/node-v${_node_version}.tar.gz


## - Install
## -
gunzip < node-v${_node_version}.tar.gz | tar -xf -
cd  node-v${_node_version}

./configure --prefix=/usr/local/node-v${_node_version}
make
make install

ln -s node-v${_node_version} /usr/local/node

## - Add bin directory of node to the PATH environment
## -
## - Edit /etc/profile
## -
## - Add befor exporting PATH variable:
## -
## -
## -    checkdir="/usr/local/node/bin"
## -    if [ -d $checkdir ]; then
## -       PATH=$PATH:$checkdir
## -    fi
vim /etc/profile


## - Install manpages
## -
## - Manpages
## -
if ! grep /usr/local/node/share/man /etc/manpath.config > /dev/null 2<&1 ; then
   echo >> /etc/manpath.config
   echo "MANDATORY_MANPATH /usr/local/node/share/man /var/cache/man" >> /etc/manpath.config
   echo "MANPATH_MAP /usr/local/node/bin /usr/local/node/share/man" >> /etc/manpath.config
   echo "MANDB_MAP /usr/local/node/share/man /var/cache/man" >> /etc/manpath.config
fi




## -------------------------------------------------
## - Install etherpad-lite



## - Create MySQL databse
## -
## -   db_name: $_etherpad_db_name
## -   db_user: $_etherpad_db_user
## -   db_pass: $_etherpad_db_pass
## -
mysql $mysql_credential_args -N -s -e \
   "CREATE DATABASE IF NOT EXISTS $_etherpad_db_name CHARACTER SET utf8 COLLATE utf8_general_ci"

mysql $mysql_credential_args -N -s -e \
   "GRANT ALL PRIVILEGES ON $_etherpad_db_name.* TO '$_etherpad_db_user'@'127.0.0.1' IDENTIFIED BY '$_etherpad_db_pass'"
mysql $mysql_credential_args -N -s -e \
   "GRANT ALL PRIVILEGES ON $_etherpad_db_name.* TO '$_etherpad_db_user'@'localhost' IDENTIFIED BY '$_etherpad_db_pass'"
mysql $mysql_credential_args -N -s -e \
   "GRANT ALL PRIVILEGES ON $_etherpad_db_name.* TO '$_etherpad_db_user'@'$_ipv4' IDENTIFIED BY '$_etherpad_db_pass'"

mysql $mysql_credential_args -N -s -e \
   "INSERT INTO `db` VALUES ('$_ipv4','$_etherpad_db_pass','$_etherpad_db_user','Y','Y','Y','Y','Y','Y','N','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y')"
mysql $mysql_credential_args -N -s -e \
   "INSERT INTO `db` VALUES ('127.0.0.1','$_etherpad_db_pass','$_etherpad_db_user','Y','Y','Y','Y','Y','Y','N','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y')"

mysql $mysql_credential_args -N -s -e "FLUSH PRIVILEGES"


## - Create user $_etherpad_user for etherpad
## -
adduser --system --home=/var/www/etherpad-lite/ --group $_etherpad_user


## - Get etherpad-lite
## -
## - Downlouad via
## -    https://github.com/ether/etherpad-lite
## - or clone yoursef via git cone
## -
cd /var/www
git clone git://github.com/ether/etherpad-lite.git $_etherpad_instance

cd ${_etherpad_dir}

cp ${_etherpad_dir}/settings.json.template \
   ${_etherpad_dir}/settings.json

mkdir -p ${_etherpad_dir}/log
chown -R $_etherpad_user:$_etherpad_user ${_etherpad_dir}


## - Adjust settings.json
## -
## -    "port" : ${_etherpad_port},
## -
## - Setup a sessionKey (secure string, at least 10 characters)
## -    "sessionKey" : "bHT7JCwnFVXcz4Jvqk9qLsd9",
## -
## - Setup database. comment in type dirty section an uncomment/create
## - section for MySQL. Note, if no tcp binding on mysql exists and only
## - mysql is only listening on linux socket, use "port" instead of "host"
## -
## -    "dbType" : "mysql",
## -    "dbSettings" : {
## -        "user"    : "$_etherpad_db_user",
## -        "host"    : "<IP-Address>",
## -        "password": "$_etherpad_db_pass",
## -        "database": "$_etherpad_db_name"
## -    },
## -    NOTE !!:
## -    If running on VServer guest System, set host to Vservers IP-Address.
## -    "127.0.0.1" does not work and "localhost" does not work in conjunction
## -    wilt some plugins (i.e ep_frontend_community)
## -
## - At least setup an admin user to access /admin url. Uncomment/create
## - section "users"
## -
## -   "users": {
## -     "admin": {
## -       "password": "20admin14",
## -       "is_admin": true
## -     },
## -
## - We have installed abiword, so enable Abiword 
## - for advanced import/export features of pads like PDF,
## -
## -   "abiword" : "/usr/bin/abiword",
## -
vim ${_etherpad_dir}/settings.json


## - Configure the "safeRun.sh"-script to ensure getting
## - email email notifications if there are problems with 
## - the applications.
## -
## - This script also ensures that ep-lite is automatically 
## - restarting after an error happens
## -
## - Set/Replace
## -
## -    ERROR_HANDLING=1
## -    EMAIL_ADDRESS="argus@oopen.de"
## -
vim ${_etherpad_dir}/bin/safeRun.sh


## - Start at first time and let etherpad make initial configurations
## -
su -c "PATH=/usr/local/node/bin:$PATH ${_etherpad_dir}/bin/run.sh" -s /bin/bash ${_etherpad_user}

## - If initial configuration is done, you will see output like
## -    You can access your Etherpad instance at http://0.0.0.0:9001/
## - type <Ctrl>+c to break and afterwords kill left processes
## -
pkill --signal SIGTERM -u ${_etherpad_user}


## - Create startscript for etherpad-lite in folder /etc/init.d
## -
cat << EOF > /etc/init.d/${_etherpad_instance}
#!/usr/bin/env bash

### BEGIN INIT INFO
# Provides:          $_etherpad_instance
# Required-Start:    \$local_fs \$remote_fs \$network \$syslog
# Required-Stop:     \$local_fs \$remote_fs \$network \$syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: starts etherpad lite
# Description:       starts etherpad lite using start-stop-daemon
### END INIT INFO

PATH="/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/node/bin"
LOGFILE="${_etherpad_dir}/log/${_etherpad_instance}.log"
EPLITE_DIR="${_etherpad_dir}"
EPLITE_BIN="bin/safeRun.sh"
USER="$_etherpad_user"
GROUP="$_etherpad_group"
DESC="Etherpad Lite"
NAME="$_etherpad_instance"

set -e

. /lib/lsb/init-functions

start() {

  ## - Already running ?
  # -
  if [ -f "/var/run/\$NAME.pid" ]; then
    _pids=\$(cat /var/run/\$NAME.pid | tr '\n' ' ')
    for _pid in \$_pids ; do
      if [ -d "/proc/\$_pid" ];then
        echo "\$DESC is already running. Exiting.."
        return
      fi
    done
    rm -f /var/run/\$NAME.pid
  fi

   _pids=\$(ps  --no-headers  ax | grep \$EPLITE_DIR/\$EPLITE_BIN | grep -v grep | awk '{print\$1}' | tr '\n' ' ')
   if [ -n "\$_pids" ]; then
   echo "Some older \$DESC processes are running. I will stop them first.."
   for pid in \$_pids ;do
      killtree \$pid 15
      sleep 0.5
   done
   echo "done"
   fi

  ## - Start now..
  echo "Starting \$DESC... "
  
   start-stop-daemon --start --chuid "\$USER:\$GROUP" --background \\
      --make-pidfile --pidfile /var/run/\$NAME.pid --exec \\
      \$EPLITE_DIR/\$EPLITE_BIN -- \$LOGFILE || true
  echo "done"
}

#We need this function to ensure the whole process tree will be killed
killtree() {
    local _pid=\$1
    local _sig=\${2-TERM}
    for _child in \$(ps -o pid --no-headers --ppid \${_pid}); do
        killtree \${_child} \${_sig}
    done
    if ps -o pid --no-headers  ax | grep \${_pid} > /dev/null ; then
      kill -\${_sig} \${_pid}
    fi
}

stop() {
  echo "Stopping \$DESC... "
  if [ -f "/var/run/\$NAME.pid" ]; then
    while test -d /proc/\$(cat /var/run/\$NAME.pid); do
      killtree \$(cat /var/run/\$NAME.pid) 15
      sleep 0.5
    done
    rm -f /var/run/\$NAME.pid
  fi
  for pid in \$(ps  --no-headers  ax | grep \$EPLITE_DIR/\$EPLITE_BIN | grep -v grep | awk '{print\$1}' | tr '\n' ' ');do
    killtree \$pid 15
    sleep 0.5
  done
  echo "done"
}

status() {
  status_of_proc -p /var/run/\$NAME.pid "" "$_etherpad_instance" && exit 0 || exit \$?
}

case "\$1" in
  start)
     start
     ;;
  stop)
    stop
     ;;
  restart)
     stop
     start
     ;;
  status)
     status
     ;;
  *)
     echo "Usage: \$NAME {start|stop|restart|status}" >&2
     exit 1
     ;;
esac

exit 0
EOF

chmod 755 /etc/init.d/$_etherpad_instance


m# - Make etherpad start at boottime
## -
update-rc.d ${_etherpad_instance} defaults


## - Note:
## - etherpad-lite is logging into file {_etherpad_dir}/log/${_etherpad_instance}.log

## - UPDATE etherpad-lite
## -
## - !! Note !!
## - We uses a system user for etherpad-lite processes. So you
## - cannot login as that user. For Updating etherpad-lite use the 
## - following command
## -    su -c "cd ${_etherpad_dir} ; git pull origin" -s /bin/bash ${_etherpad_user}
## -
su -c "cd ${_etherpad_dir} ; git pull origin" -s /bin/bash ${_etherpad_user}


## -------------------------------------------------
## - Use nginx as proxy
## -

## - Create host config
## -
## - Notice !!
## -
## -    - Don't forget to place the ssl certificate/key
## -
## -    - include intermediate cert(s) into cert file:
## -         first:   site certificate
## -         second:  intermidiate certificate
## -
cat << EOF > /etc/nginx/sites-available/${_hostname}.conf
server {

   listen $_ipv4:80;
   listen $_ipv4:443 ssl;
   listen [$_ipv6]:80 ; ## listen for ipv6
   listen [$_ipv6]:443 ssl ; ## listen for ipv6

   server_name $_hostname;

   root $_etherpad_dir;

   location = /favicon.ico {
      return 204;
      log_not_found off;
      access_log off;
   }

   location = /robots.txt {
      log_not_found off;
      access_log off;
   }

   # Deny all attempts to access hidden files such as .htaccess, .htpasswd,
   # .DS_Store (Mac).
   location ~ /\. {
      return 444;
      access_log off;
      log_not_found off;
   }

   #include standard.conf;

   ssl_certificate ssl_keys/oopen.de.chained.crt;
   ssl_certificate_key ssl_keys/oopen.de.key;

   if (\$scheme = http) {
      return 301 https://\$server_name\$request_uri;
   }

   #auth_basic           "closed site";
   #auth_basic_user_file /etc/nginx/.htpasswd_etherpad;

   ## - Handle pad URLs here
   ## -
   location / {
      proxy_pass http://${_etherpad_instance};
      proxy_set_header       Host \$host;
      proxy_buffering off;
   }
}

upstream $_etherpad_instance {
   server $_etherpad_host:$_etherpad_port;
}
EOF

ln -s ../sites-available/${_hostname}.conf /etc/nginx/sites-enabled/


## - robots.txt
## -
cat << EOF > ${_etherpad_dir}/robots.txt
User-agent: *
Disallow: /
EOF

chown ${_etherpad_user}:${_etherpad_user} ${_etherpad_dir}/robots.txt


## - Further adjusting settings.json
## -
## - Bind to 127.0.0.1
## -    "ip": "127.0.0.1",
## -
## - We will use NginX as a proxy, so set this to true
## -    "trustProxy": true,
## -
vim ${_etherpad_dir}/settings.json


## - Start etherpad-lite
## -
/etc/init.d/$_etherpad_instance start



## -------------------------------------------------
## - Install Plugin adminpads
## -    (ep_adminpads)

## - Install adminpads via admin interface -> Plugin Manager
## -
## -    URL...: https://${_hostname}/admin
# -



## -------------------------------------------------
## - Install community frontend
## -    (Plugin ep_frontend_community)


## - Note:
## -
## - host-part of db settings in settings.json must have:
## -    "host"    : "<IP-Address>"
## -
## -    "port"    : "<path/to//mysql.sock>" DOES NOT work
## -

## - Install adminpads via admin interface -> Plugin Manager
## -
## -    URL...: https://${_hostname}/admin




## - Prerequisites:
## -
## - Create needed database tables:
## -
mysql $mysql_credential_args $_etherpad_db_name -N -s -e \
"DROP TABLE IF EXISTS GroupPads;
 CREATE TABLE GroupPads (
    UserID int(11) DEFAULT '1',
    GroupID int(11) NOT NULL,
    PadName varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL, 
    PRIMARY KEY (GroupID,PadName) 
 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;"

mysql $mysql_credential_args $_etherpad_db_name -N -s -e \
"DROP TABLE IF EXISTS Groups;
 CREATE TABLE Groups ( 
    groupID int(11) NOT NULL AUTO_INCREMENT, 
    name varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL DEFAULT '', 
    PRIMARY KEY (groupID,name) 
 ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;"

mysql $mysql_credential_args $_etherpad_db_name -N -s -e \
"DROP TABLE IF EXISTS NotRegisteredUsersGroups;
 CREATE TABLE NotRegisteredUsersGroups ( 
    email varchar(255) NOT NULL, 
    groupID int(11) NOT NULL ) 
 ENGINE=InnoDB DEFAULT CHARSET=utf8;"

mysql $mysql_credential_args $_etherpad_db_name -N -s -e \
"DROP TABLE IF EXISTS User;
 CREATE TABLE User ( 
    userID int(11) NOT NULL AUTO_INCREMENT, 
    name varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL DEFAULT '',  
    pwd varchar(255) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL, 
    considered tinyint(11) DEFAULT NULL, 
    SSO tinyint(4) DEFAULT NULL, 
    FullName varchar(255) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL, 
    considerationString varchar(50) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL, 
    salt varchar(255) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL, 
    active int(1) DEFAULT NULL, isAdmin int(1) NOT NULL DEFAULT '0', 
    PRIMARY KEY (userID,name) 
 ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;"

mysql $mysql_credential_args $_etherpad_db_name -N -s -e \
"DROP TABLE IF EXISTS UserGroup;
 CREATE TABLE UserGroup ( 
    userID int(11) NOT NULL DEFAULT '0', 
    groupID int(11) NOT NULL DEFAULT '0', 
    Role int(11) DEFAULT NULL, 
    PRIMARY KEY (userID,groupID) 
 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;"

## - Note:
## -    Setup the Pad Administrator with full rights. You
## -    can login, with the following credentials:
## -
## -       username:  $_etherpad_admin
## -       password:  admin
## -
mysql $mysql_credential_args $_etherpad_db_name -N -s -e \
"INSERT INTO User VALUES ( 1,'$_etherpad_admin','53e8f649c9bfbccf8f8e2b588d05de8ce26f26228a9cc9340cdc8c5f9b1a0d1e', 1,0,'Pad System Adminstrator','fGREpQX1cwnUqv3fsqHPkjP3WtlG1ZsXFFx6v0mR','EYEcciC6Nk',1,1 );"

## - Install etherpad plugin frontend_community via admin interface of etherpad
## - 
## -    url: https://etherpad.oopen.de/admin/plugins
## -

## - Adjust /var/www/etherpad-lite/node_modules/ep_frontend_community/email.json
## -
## -    "smtp": "false",
## -    ..
## -    "invitationfrom": "admin@oopen.de"
## -    ..
## -    "registrationfrom": "admin@oopen.de"
## -    ..
## -    "resetfrom": "admin@oopen.de",
## -
vim ${_etherpad_dir}/node_modules/ep_frontend_community/email.json


## - Further adjusting settings.json
## -
## - we want users to authenticate
## -    "requireAuthorization": true,
## -
## - don't allow public pads, only group pads are allowed
## -    "requireSession" : true,
## -
vim ${_etherpad_dir}/settings.json


## - Logo
## -
## - You can have your own logo for the pad header. The logo image file
## - is placed at:
## -
## -    ${_etherpad_dir}/node_modules/ep_frontend_community/static/images/logo.png
## -


## -------------------------------------------------
## - Install Plugin aa_file_menu_toolbar
## -    (ep_aa_file_menu_toolbar)

## - Install aa_file_menu_toolbar via admin interface -> Plugin Manager



## -------------------------------------------------
## - Install Plugin copy_paste_select_all
## -    (ep_copy_paste_select_all)

## - Install copy_paste_select_all via admin interface -> Plugin Manager



## -------------------------------------------------
## - Install Plugin headings
## -    (ep_headings)

## - Install headings via admin interface -> Plugin Manager



## -------------------------------------------------
## - Install Plugin set_title_on_pad
## -    (ep_set_title_on_pad)

## - Install set_title_on_pad via admin interface -> Plugin Manager



## -------------------------------------------------
## - Install Plugin page_view
## -    (ep_page_view)

## - Install page_view via admin interface -> Plugin Manager



## -------------------------------------------------
## - Install Plugin page_ruler
## -    (ep_page_ruler)

## - Install page_ruler via admin interface -> Plugin Manager



## -------------------------------------------------
## - Install Plugin fileupload
## -    (ep_fileupload)

## - Install fileupload via admin interface -> Plugin Manager


## xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx


## -------------------------------------------------
## - Install plugin imageconvert
## -    (Plugin ep_imageconvert)

## - Install Prerequisites:
## -
apt-get install imagemagick poppler-utils ghostscript sed



## -------------------------------------------------
## - Install Plugin sketchspace_pdfbackground
## -    (ep_sketchspace_pdfbackground)

## - Install sketchspace_pdfbackground via admin interface -> Plugin Manager


## - Install plugin imageconvert via via admin interface of etherpad



## -------------------------------------------------
## - Install Plugin print
## -    (ep_print)

## - Install print via admin interface -> Plugin Manager



## xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx


## - Homepage etherpad
## -
## -    http://etherpad.org/

## - Wiki etherpad
## -
## -    https://github.com/ether/etherpad-lite/wiki


## - Install etherpad:
## -
## -    https://github.com/ether/etherpad-lite/blob/master/README.md
## -    https://github.com/ether/etherpad-lite/wiki/How-to-put-Etherpad-Lite-behind-a-reverse-Proxy


## - How to deploy Etherpad Lite as a service - means startup script at boot time
## -
## -    https://github.com/ether/etherpad-lite/wiki/How-to-deploy-Etherpad-Lite-as-a-service
## -


## - How to use Etherpad Lite with MySQL:
## -
## -    https://github.com/ether/etherpad-lite/wiki/How-to-use-Etherpad-Lite-with-MySQL
## -    https://github.com/ether/etherpad-lite/wiki/How-to-migrate-the-database-from-Etherpad-to-Etherpad-Lite



