 #!/bin/sh

echo "Downloading Sandstorm-Agent"
aws s3 cp s3://twitch-sandstorm/sandstorm-agent.rpm /tmp/sandstorm-agent.rpm || (echo "Failed to download sandstorm-agent.rpm, do you have the correct permissions?" && exit 1)

yum install -y /tmp/sandstorm-agent.rpm || (echo "No package available" && exit 1)

eval  $(/opt/elasticbeanstalk/containerfiles/support/generate_env | sed 's/$/;/')

# Replaces TWITCH_ENV with $TWITCH_ENV environment variable
sed -i "s/{TWITCH_ENV}/${TWITCH_ENV}/g" /etc/sandstorm-agent/templates.d/*
sed -i "s/{TWITCH_ENV}/$TWITCH_ENV/g" /etc/sandstorm-agent/conf.d/*.conf
sed -i "s/{ENVIRONMENT}/${ENVIRONMENT}/g" /etc/sandstorm-agent/templates.d/*
sed -i "s/{ENVIRONMENT}/$ENVIRONMENT/g" /etc/sandstorm-agent/conf.d/*.conf

# Replaces TWITCH_ROLE with $TWITCH_ROLE environment variable
# need to use | here since roles contain "/"
sed -i "s|{TWITCH_ROLE}|${TWITCH_ROLE}|g" /etc/sandstorm-agent/templates.d/*
sed -i "s|{TWITCH_ROLE}|$TWITCH_ROLE|g" /etc/sandstorm-agent/conf.d/*.conf

echo "Setting Up Monit"

mkdir -p /var/lib/monit

monit
sleep 5
monit reload
sleep 5

echo "Restarting Sandstorm-Agent"
monit restart sandstorm-agent



# Clean Up
