#!/usr/bin/env bash

if [ "$EUID" -ne 0 ]; then
  echo "Invoked as non-root, sudoing..."
  sudo -- wynurz "$@"
  exit $?
fi

if [ $1 == "java" ]; then
    # Oracle Java JRE
    apt-get install -y debconf-utils
    echo "deb http://ppa.launchpad.net/webupd8team/java/ubuntu trusty main" > /etc/apt/sources.list.d/webupd8team-java.list
    echo "deb-src http://ppa.launchpad.net/webupd8team/java/ubuntu trusty main" >> /etc/apt/sources.list.d/webupd8team-java.list
    apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys EEA14886
    apt-get update
    echo debconf shared/accepted-oracle-license-v1-1 select true |  debconf-set-selections
    apt-get install -y oracle-java8-installer
fi


if [ $1 == "node4" ]; then
    apt-get install -y curl git build-essential unzip
    curl -sL https://deb.nodesource.com/setup_4.x | bash -
    apt-get install -y nodejs
fi

if [ $1 == "node5" ]; then
    apt-get install -y curl git build-essential unzip
    curl -sL https://deb.nodesource.com/setup_5.x | bash -
    apt-get install -y nodejs
fi

if [ $1 == "jdk" ]; then
    cd /home/vagrant
    wget -nv http://dev.dms-serwis.com.pl/misc/jdk-8u121-linux-x64.tar.gz
    tar xzf jdk-8u121-linux-x64.tar.gz
    rm -f jdk-8u121-linux-x64.tar.gz
    update-alternatives --install /usr/bin/java java /home/vagrant/jdk1.8.0_121/bin/java 100
    update-alternatives --install /usr/bin/javac javac /home/vagrant/jdk1.8.0_121/bin/javac 100
    update-alternatives --install /usr/bin/jar jar /home/vagrant/jdk1.8.0_121/bin/jar 100
    update-alternatives --install /usr/bin/jarsigner jarsigner /home/vagrant/jdk1.8.0_121/bin/jarsigner 100
fi

if [ $1 == "cassandra" ]; then
    # Install Apache Cassandra
    echo "deb http://debian.datastax.com/community stable main" > /etc/apt/sources.list.d/cassandra.sources.list
    curl -L http://debian.datastax.com/debian/repo_key | apt-key add -
    apt-get update
    apt-get install -y cassandra=3.0.9 dsc30 cassandra-tools

    (sleep 30 &&
     service cassandra stop &&
     rm -rf /var/lib/cassandra/*) &
fi

if [ $1 == "zookeeper" ]; then
    apt-get install -y zookeeper zookeeperd
    (service zookeeper stop &&
     sleep 20 &&
     service zookeeper stop) &
fi

if [ $1 == "rabbitmq" ]; then
    apt-get install -y rabbitmq-server=3.3.5-1.1
    service rabbitmq-server stop &
fi

if [ $1 == "postgresql" ]; then
    apt-get install -y postgresql-9.4
    (echo "host all all 0.0.0.0/0 md5" >> /etc/postgresql/9.4/main/pg_hba.conf &&
    echo "listen_addresses = '*'" >> /etc/postgresql/9.4/main/postgresql.conf &&
    sudo -u postgres psql --c "ALTER USER postgres WITH PASSWORD 'postgres';" &&
    systemctl stop postgresql.service) &
fi