#!/usr/bin/env bash

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

set -e

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

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

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


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

## Check if something is already on the port
if [ -n "${PORT}" ] \
  && lsof -Pi ":${PORT}" -sTCP:LISTEN -t >/dev/null \
  && ! systemctl is-active --quiet "${SERVICE}"; then
  echo -e "${SPACER}${YELLOW}[i]${RESET} Something is already using port: ${PORT}/tcp"
  echo "${SPACER}"
  lsof -Pi ":${PORT}" -sTCP:LISTEN \
  | sed 's/^/┃   /'
  echo "${SPACER}"
  ps -f "$(lsof -Pi ":${PORT}" -sTCP:LISTEN -t)" \
  | sed 's/^/┃   /'
  echo "${SPACER}"
  echo "${FOOTER}"
  exit 1
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 (echo > /dev/tcp/127.0.0.1/"${PORT}") 2>/dev/null; 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"
  command -v xdg-open > /dev/null \
    && nohup 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

if echo "${CREDENTIALS}" | grep : >/dev/null; then
  echo "${SPACER}"
  echo "${SPACER} Default credentials:"
  echo "${SPACER}   user: ${UNDERLINE}${CREDENTIALS%:*}${RESET}"
  echo "${SPACER}   password: ${UNDERLINE}${CREDENTIALS#*:}${RESET}"
fi

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