#!/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"
BURPUI="/tmp/burpui.dev.tar.gz"

cd

apt-get remove -y python-cffi
apt-get update
apt-get install -y libssl-dev libmysqlclient-dev libpq-dev

# Install burp-ui
pip install --upgrade pip
pip install --upgrade $BURPUI
pip install ujson
pip install gevent
pip install redis
pip install flask-limiter
pip install mysqlclient
pip install psycopg2
pip install Flask-Session
pip install Flask-SQLAlchemy
pip install Flask-Migrate
pip install sqlalchemy-utils
pip install celery

# Create burp-ui User
useradd -r -m -d /var/lib/burpui -c 'Burp-UI daemon user' -u 5337 burpui

mkdir -p /var/log/gunicorn
chown -R burpui: /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

mkdir -p /etc/burp
cp ${CONFIG_DIR}/burp-ui/burpui.cfg /etc/burp/burpui.cfg
rand=$(dd if=/dev/urandom bs=256 count=1 2>/dev/null | base64 | sed ':a;N;$!ba;s/\n//g')
perl -i -pe "s#\@RANDOM\@#$rand#" /etc/burp/burpui.cfg

# patch demo with piwik
REP=$(cat ${CONFIG_DIR}/patch/piwik.patch)
perl -i -pe "s#^.*\@DEMO\@.*\$#$REP#" /usr/local/lib/python2.7/dist-packages/burpui/templates/layout.html

# compile translations
su -l burpui -c "/usr/local/bin/bui-manage compile_translation"

# cleanup
rm -rf /var/lib/apt/lists/*
