#!/bin/bash
# This script installs storm and its dependencies
# More documentation on the README.md file

if [ "${DIB_DEBUG_TRACE:-0}" -gt 0 ]; then
    set -x
fi
set -eu
set -o pipefail

tmp_dir=/tmp/storm

echo "Creating Storm User"
groupadd -g 53001 storm
mkdir -p /app/home/storm
useradd -u 53001 -g 53001 -d /app/home/storm -s /bin/bash storm -c "Storm service account"
chmod 700 /app/home/storm
chage -I -1 -E -1 -m -1 -M -1 -W -1 -E -1 storm

echo "Extracting Storm"
# The user is not providing his own Storm distribution package
if [ -z "${STORM_DOWNLOAD_URL:-}" ]; then

# Check storm version
    case "$DIB_STORM_VERSION" in
        0.9.*)
            STORM_DOWNLOAD_URL="http://archive.apache.org/dist/incubator/storm/apache-storm-$DIB_STORM_VERSION-incubating/apache-storm-$DIB_STORM_VERSION-incubating.tar.gz"
            STORM_FOLDER=apache-storm-$DIB_STORM_VERSION-incubating
        ;;
        1.*)
            STORM_DOWNLOAD_URL="https://archive.apache.org/dist/storm/apache-storm-$DIB_STORM_VERSION/apache-storm-$DIB_STORM_VERSION.tar.gz"
            STORM_FOLDER=apache-storm-$DIB_STORM_VERSION
        ;;
        *)
            echo -e "WARNING: Storm version $DIB_STORM_VERSION not supported."
            echo -e "WARNING: make sure STORM_DOWNLOAD_URL points to a compatible Storm version."
            exit 1
        ;;
    esac
fi

storm_file=$(basename "$STORM_DOWNLOAD_URL")
echo $storm_file
cd /usr/local
tar -xvf $tmp_dir/$storm_file
chown -R storm:storm $STORM_FOLDER
ln -s $STORM_FOLDER storm
rm -r $tmp_dir


echo "Configuring Storm home"
mkdir -p /app/storm
chown -R storm:storm /app/storm
chmod 750 /app/storm

echo "Installing Supervisor Daemon"

update-rc.d supervisor defaults
chmod 600 /etc/supervisor/supervisord.conf

mkdir -p /var/log/storm
chown -R storm:storm /var/log/storm

apt-get install -y python-dev
apt-get install -y python-pip

if [ "$DIB_RELEASE" = "xenial" ]; then
    apt-get install -y python-setuptools # See launchpad bug 1556681
    apt-get install -y python-wheel
fi

pip install pyleus
