#!/bin/env sh

set -e

NEO4J_PORT=7474

RESET='\033[0m'
UNDERLINE='\033[1;4m'
RED='\033[1;31m'
GREEN='\033[1;32m'
YELLOW='\033[1;33m'

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

echo "\n ${YELLOW}[*]${RESET} Starting PostgreSQL service"

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

echo
echo " ${YELLOW}[*]${RESET} Creating Database"

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

echo
echo " ${YELLOW}[*]${RESET} Starting neo4j"
! neo4j status && neo4j start

echo
echo " ${GREEN}[i]${RESET} ${BOLD}You need to change the default password for neo4j${RESET}"
echo "     Default credentials:"
echo "         user: ${UNDERLINE}neo4j${RESET}"
echo "         password: ${UNDERLINE}neo4j${RESET}"
echo
echo " ${RED}[!] IMPORTANT:${RESET} Once you have setup the new password, please update ${GREEN}/etc/bhapi/bhapi.json${RESET} with the new password before running bloodhound"

until curl -s "http://localhost:${NEO4J_PORT}/" >/dev/null; do printf ...; sleep .5; done
echo "\n opening ${YELLOW}${UNDERLINE}http://localhost:${NEO4J_PORT}/${RESET}"
xdg-open "http://localhost:${NEO4J_PORT}/"
