#!/bin/sh

set -e

if [ `id -u` -ne 0 ]; then
    echo "Error: $0 must be run as root" 1>&2
    exit 1
fi

systemctl start postgresql

runuser -u postgres -- /usr/share/defectdojo/create-database-defectdojo

if [ ! -e /var/lib/defectdojo/key ]; then
    runuser -u _defectdojo -- cat /dev/urandom | LC_ALL=C tr -dc a-zA-Z0-9 | head -c 22 >/var/lib/defectdojo/key
fi

cd /usr/lib/defectdojo
echo -n "Waiting for database to be reachable "
until echo "select 1;" | python3 manage.py dbshell > /dev/null
do
  echo -n "."
  sleep 1
done
echo

echo "Making migrations"
python3 manage.py makemigrations dojo
echo "Migrating"
python3 manage.py migrate

ADMIN_EXISTS=$(runuser -u _defectdojo -- psql --quiet --tuples-only --no-align -c "SELECT 1 FROM auth_user WHERE username='admin'" defectdojo)

if [ "${ADMIN_EXISTS}" != "1" ]; then
    export DD_ADMIN_PASSWORD="$(cat /dev/urandom | LC_ALL=C tr -dc a-zA-Z0-9 | \
	head -c 22)"
    echo "Admin password: ${DD_ADMIN_PASSWORD}"
    cat <<EOD | python3 manage.py shell
import os
from django.contrib.auth.models import User
User.objects.create_superuser(
  'admin',
  'admin@defectdojo.local',
  os.getenv('DD_ADMIN_PASSWORD'),
  first_name='Admin',
  last_name='User'
)
EOD

    python3 manage.py loaddata system_settings initial_banner_conf product_type test_type \
       development_environment benchmark_type benchmark_category benchmark_requirement \
       language_type objects_review regulation initial_surveys role

    echo "UPDATE dojo_system_settings SET jira_webhook_secret='$uuidgen'" | python3 manage.py dbshell

    python3 manage.py installwatson
    python3 manage.py migrate_textquestions
    python3 manage.py collectstatic --noinput
fi

python3 manage.py initialize_test_types
python3 manage.py initialize_permissions


systemctl start defectdojo

if ! systemctl is-active --quiet defectdojo; then
  echo "ERROR: defectdojo failed to start" 1>&2
  systemctl --no-pager -l status defectdojo
  exit 1
fi

systemctl start defectdojo-uwsgi

systemctl start defectdojo-celerybeat
systemctl start defectdojo-celeryworker

if [ -n "${DD_ADMIN_PASSWORD}" ]; then
    echo "Please note the generated password:"
    echo "The password for the user 'admin' is $DD_ADMIN_PASSWORD"
else
    echo "If you don't remember the password for the user admin, you can create a new superuser with:"
    echo "cd /usr/lib/defectdojo && sudo -u _defectdojo -- python3 manage.py createsuperuser"
fi

echo "\n Opening Web UI: http://127.0.0.1:42003"
xdg-open "http://127.0.0.1:42003" 2>/dev/null >/dev/null &
