#!/usr/bin/env bash

# Syntax: service-start <service> <port> [<url>]

set -e

SERVICE="$1"
PORT="$2"
URL=${3:-"http://127.0.0.1:${PORT}"}

[ -z "${SERVICE}" ] && exit

RESET=$'\033[0m'
BOLD=$'\033[1m'
UNDERLINE=$'\033[1;4m'
RED=$'\033[1;31m'
GREEN=$'\033[1;32m'
YELLOW=$'\033[1;33m'
HEADER="┏━(${RED}Message from Kali developers${RESET})"
SPACER='┃ '
FOOTER='┗━'


echo "${HEADER}"
echo "${SPACER}"

## Check if something is already on the port
if lsof -Pi :${PORT} -sTCP:LISTEN -t >/dev/null ; then
  echo -e "${SPACER}${YELLOW}[i]${RESET} Something is already using port: ${PORT}/tcp"
  lsof -Pi :${PORT} -sTCP:LISTEN \
  | sed 's/^/┃   /'
  echo "${SPACER}"
  ps -f $(lsof -Pi :${PORT} -sTCP:LISTEN -t) \
  | sed 's/^/┃   /'
  echo "${SPACER}"
fi

## Start service
if ! systemctl is-active --quiet "${SERVICE}"; then
  echo "${SPACER}Please wait for the ${SERVICE} service to start"
  systemctl start "${SERVICE}"
  if [ -n "${PORT}" ]; then
    echo -n "${SPACER}"
    until nc 127.0.0.1 "${PORT}" -z; do echo -n ..; sleep 1; done
    echo
  fi
fi

## Display information to user
if [ -n "${PORT}" ] && curl -s -k -L "${URL}" >/dev/null; then
  ## Open browser
  echo "${SPACER}${GREEN}[*]${RESET} Web UI: ${GREEN}${UNDERLINE}${URL}${RESET}"
  echo "${SPACER}${YELLOW}[i]${RESET} You might need to refresh your browser once it opens"
  xdg-open "${URL}" &>/dev/null
else
  ## Check service status
  echo "${SPACER}${BOLD}${UNDERLINE}Service status:${RESET}"
  systemctl --no-pager -l status "${SERVICE}" \
  | sed 's/^/┃   /'
fi

echo "${SPACER}"
echo "${FOOTER}"
