#!/bin/bash
# Build: @build@
set -e

SETUP_DIR="/app/setup"
CONFIG_DIR="${SETUP_DIR}/config"
BURPUI="https://burpui.ziirish.me/builds/burp-ui.dev.tar.gz"

apt-get update
DEBIAN_FRONTEND=noninteractive apt-get install -y wget python2.7-dev git python-pip libffi-dev libmysqlclient-dev libpq-dev libpq5

echo "deb http://ziirish.info/repos/debian/jessie zi-stable main" >/etc/apt/sources.list.d/ziirish.list
wget https://ziirish.info/repos/debian.gpg -O- | apt-key add -
apt-get update

DEBIAN_FRONTEND=noninteractive apt-get remove -y python-cffi
DEBIAN_FRONTEND=noninteractive apt-get install -y libssl-dev burp-client

# Install burp-ui
pip install --upgrade pip
cd /burp-ui
git submodule update --init
pip install -r requirements.txt
python setup.py sdist
pip install ujson
pip install gevent
pip install redis
pip install mysqlclient
pip install psycopg2
pip install flask-limiter
pip install Flask-Session
pip install Flask-SQLAlchemy
pip install Flask-Migrate
pip install sqlalchemy-utils
pip install celery
pip install dist/*.tar.gz

cffi=$(grep cffi requirements.txt)
cd
rm -rf /burp-ui

mkdir -p /var/log/gunicorn

# configure supervisord log rotation
cat > /etc/logrotate.d/supervisord <<EOF
/var/log/supervisor/*.log {
  weekly
  missingok
  rotate 52
  compress
  delaycompress
  notifempty
  copytruncate
}
EOF

# configure gunicorn log rotation
cat > /etc/logrotate.d/gunicorn <<EOF
/var/log/gunicorn/*.log {
  daily
  missingok
  rotate 14
  compress
  delaycompress
  notifempty
  copytruncate
}
EOF

# configure supervisord to start crond
cat > /etc/supervisor/conf.d/cron.conf <<EOF
[program:cron]
priority=20
directory=/tmp
command=/usr/sbin/cron -f
user=root
autostart=false
autorestart=true
stdout_logfile=/var/log/supervisor/%(program_name)s.log
stderr_logfile=/var/log/supervisor/%(program_name)s.log
EOF

# configure celery worker                                                       
cat > /etc/supervisor/conf.d/bui-celery.conf <<EOF
[program:bui-celery]
priority=20
directory=/tmp
command=/usr/local/bin/bui-celery --beat -s /var/lib/burpui/celerybeat-schedule
user=burpui
autostart=false
autorestart=true
stdout_logfile=/var/log/supervisor/%(program_name)s.log
stderr_logfile=/var/log/supervisor/%(program_name)s.log
EOF

cp ${CONFIG_DIR}/gunicorn.d/burp-ui /etc/gunicorn.d/burp-ui

# this is used in case nothing is monted on /etc/burp
mkdir -p /etc/burp/clientconfdir
cp ${CONFIG_DIR}/burp-ui/burpui.cfg /etc/burp/burpui.cfg

cat ${CONFIG_DIR}/burp/burp.conf >/etc/burp/burp.conf
cat ${CONFIG_DIR}/burp/burp-server.conf >/etc/burp/burp-server.conf
rm -rf /etc/burp/clientconfdir/*
echo "password = abcdefgh" >/etc/burp/clientconfdir/agent

touch /etc/burp/this_is_a_decoy_file_to_know_if_we_can_chown

# cleanup
apt-get remove -y python2.7-dev git python-pip libffi-dev libssl-dev wget libpq-dev
apt-get clean
apt-get autoclean
apt-get -y autoremove
# cffi breaks after the cleanup
/usr/local/bin/pip install $cffi
rm -rf /var/lib/apt/lists/*
