#!/bin/env sh

set -e

[ "$(id -u)" -ne 0 ] && exec sudo "$0"

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


echo
if [ -z "${DD_ADMIN_PASSWORD}" ]; then
    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

kali-service-start defectdojo 42003 admin "${DD_ADMIN_PASSWORD}"

systemctl start defectdojo-uwsgi
systemctl start defectdojo-celerybeat
systemctl start defectdojo-celeryworker
