#!/bin/bash

# Fix up the logstash options
CPUS=`grep proc /proc/cpuinfo | wc -l`
HALFMEM=`grep MemTotal: /proc/meminfo |awk '{print int($2/1024/1024/2)}'`

# -i -e always works but leaves behind a backup file with -e suffix on non-GNU sed systems
sed -E -i -e 's/^(# *)pipeline.workers:.*/pipeline.workers: '"$(( CPUS * 2 ))"'/' /etc/logstash/logstash.yml
sed -i -e '/^-Xmx/s/[0-9]*.$/'"$HALFMEM"'g/' -e '/^-Xms/s/[0-9]*.$/'"$HALFMEM"'g/' /etc/logstash/jvm.options

mkdir -p /etc/logstash/conf.d
chown -R root:root /etc/logstash
chmod -R ugo+rX /etc/logstash

apt-get update
apt-get install -y docker.io

mkdir /srv/logstash-tmp
chown 999:999 /srv/logstash-tmp
mkdir /srv/logstash-logs
chown 999:999 /srv/logstash-logs
docker run -d --net host -v /etc/logstash:/etc/logstash -v /srv/logstash-tmp:/tmp/logstash -v /srv/logstash-logs:/var/log/logstash docker.internal.justin.tv/systems/logstash:5.5 --path.settings /etc/logstash

echo "twitch_environment=${puppet_environment}" > /etc/facter/facts.d/twitch_environment.txt
echo "twitch_role=${puppet_twitch_role}" > /etc/facter/facts.d/twitch_role.txt
[ x"${puppet_twitch_team}" != x ] && echo "twitch_team=${puppet_twitch_team}" > /etc/facter/facts.d/twitch_team.txt
echo "cluster=${puppet_cluster}" > /etc/facter/facts.d/cluster.txt
echo "clean=true" > /etc/facter/facts.d/clean.txt
puppet agent --test --server=puppet.internal.justin.tv
