#!/bin/bash

## Quit on error
set -e

## Colour for bash prompt
RED="\033[01;31m"
GREEN="\033[01;32m"
YELLOW="\033[01;33m"
RESET="\033[00m"

## Check if running as root
if [[ ${EUID} -ne 0 ]]; then
  echo -e "${RED}[-]${RESET} Error: $0 must be run as root" 1>&2
  exit 1
fi

## Define PORT and URL
PORT="9392"
URL="https://127.0.0.1:${PORT}"

## Check if GVM is already running
if systemctl is-active --quiet greenbone-security-assistant gvmd ospd-openvas; then
    echo -e "${YELLOW}[i]${RESET} GVM services are already running"
    exit 0
fi

## Check if something is already on the port
if lsof -Pi :${PORT} -sTCP:LISTEN -t >/dev/null ; then
  echo -e "${RED}[-]${RESET} Something is already using port: ${PORT}/tcp" 1>&2
  lsof -Pi :${PORT} -sTCP:LISTEN
  echo ""
  ps -f $(lsof -Pi :${PORT} -sTCP:LISTEN -t)
  echo ""
  exit 1
fi

## Display information to user
echo -e "${GREEN}[>]${RESET} Please wait for the GVM services to start."
echo -e "${GREEN}[>]${RESET}"
echo -e "${GREEN}[>]${RESET} You might need to refresh your browser once it opens."
echo -e "${GREEN}[>]${RESET}"
echo -e "${GREEN}[>]${RESET}  Web UI (Greenbone Security Assistant): ${URL}\n"

## Start services
systemctl start gvmd ospd-openvas
sleep 5s
# better start gsa after
systemctl start greenbone-security-assistant

## Check services status
systemctl --no-pager -l status greenbone-security-assistant gvmd ospd-openvas

## Countdown
echo -ne "\n${GREEN}[>]${RESET} Opening Web UI (${URL}) in: "
for x in {5..1}; do
  echo -n "$x... "
  sleep 1s
done
echo ""

## Open browser
xdg-open "${URL}" 2>/dev/null >/dev/null &
