#!/bin/sh

aux_file_path="/root/.faraday/password_changed.txt"
URL="http://localhost:5985"

systemctl start postgresql

if ! sudo -u postgres -- psql -lqt | cut -d \| -f 1 | grep -qw faraday; then
    echo ">>> Init database"
    sudo faraday-manage initdb
fi

echo ">>> Start faraday.service"
sudo systemctl start faraday
sleep 3

if systemctl is-active --quiet faraday; then
    if sudo [ ! -f $aux_file_path ]; then
	sudo touch $aux_file_path
        echo "Please, set a new password for the Faraday's default user 'faraday'"
	sudo faraday-manage change-password
        xdg-open "${URL}" 2>/dev/null >/dev/null &
    else
        xdg-open "${URL}" 2>/dev/null >/dev/null &
    fi
fi
