
#!/usr/bin/env bash
# NB: local trial script has to be self-contained
# See https://sipb.mit.edu/doc/safe-shell/
set -euf -o pipefail

export DRONAHQ_LICENSE_URL="https://license.dronahq.com"

if [[ "$OSTYPE" == "linux-gnu" ]]; then
  export MAYBE_SUDO="sudo"
else
  export MAYBE_SUDO=""
fi

if [ -t 1 ]; then
  export NORMAL="$(tput sgr0)"
  export RED="$(tput setaf 1)"
  export GREEN="$(tput setaf 2)"
  export MAGENTA="$(tput setaf 5)"
  export CYAN="$(tput setaf 6)"
  export WHITE="$(tput setaf 7)"
  export BOLD="$(tput bold)"
else
  export NORMAL=""
  export RED=""
  export GREEN=""
  export MAGENTA=""
  export CYAN=""
  export WHITE=""
  export BOLD=""
fi

error_exit() {
  echo ''
  echo "${RED}${BOLD}ERROR${NORMAL}${BOLD}: $1${NORMAL}"
  shift
  while [ "$#" -gt "0" ]; do
    echo " - $1"
    shift
  done
  exit 1
}

log_step() {
  echo ''
  echo "${GREEN}${BOLD}INFO${NORMAL}${BOLD}: $1${NORMAL}"
  shift
  while [ "$#" -gt "0" ]; do
    echo " - $1"
    shift
  done
}

log_warn() {
  echo ''
  echo "${CYAN}${BOLD}WARNING${NORMAL}${BOLD}: $1${NORMAL}"
  shift
  while [ "$#" -gt "0" ]; do
    echo " - $1"
    shift
  done
}

export DISTRO=$( (lsb_release -ds || cat /etc/*release || uname -om) 2>/dev/null | head -n1)

command_present() {
  type "$1" >/dev/null 2>&1
}

dronahq_containers_present() {
  # NB: awk is to remove whitespace from `wc`
  DRONAHQ_IMAGES="$($MAYBE_SUDO docker image ls | grep 'dronahq/self-hosted' | wc -l | awk '{print $1}')"
  test "$DRONAHQ_IMAGES" -gt '0'
}

dronahq_trial_running() {
  # NB: awk is to remove whitespace from `wc`
  CONTAINERS="$($MAYBE_SUDO docker-compose ps -q | wc -l | awk '{print $1}')"
  test "$CONTAINERS" -gt '0'
}

# check and install docker and docker compose if not present

if ! command_present docker; then
  # shellcheck disable=2016
  log_warn '`docker` not found! Attempting to install. This may take a few minutes.'
  ./scripts/get-docker.sh

  if [[ $DISTRO == *"CentOS"* ]]; then
    echo 'Starting docker service'
    $MAYBE_SUDO systemctl enable docker.service
    $MAYBE_SUDO systemctl start docker.service
  fi

  if ! command_present docker; then
    if [[ "$OSTYPE" == "darwin"* ]]; then
      error_exit "please install \`docker\` manually" \
        "Instructions can be found at ${WHITE}${BOLD}https://docs.docker.com/${NORMAL}" \
        "${BOLD}Remember${NORMAL} to start the \`Docker\` app from the UI."
    else
      error_exit "please install \`docker\` manually" \
        "Instructions can be found at ${WHITE}${BOLD}https://docs.docker.com/${NORMAL}" \
        "${BOLD}Remember${NORMAL} to start the \`docker\` daemon/service."
    fi
  fi
else
  # shellcheck disable=2016
  log_step '`docker` found!'
fi

if ! command_present docker-compose; then
  # shellcheck disable=2016
  log_warn '`docker-compose` not found! Attempting to install'
  ./scripts/get-docker-compose.sh

  if [[ $DISTRO == *"CentOS"* ]]; then
    echo 'Making compose accessible by root user'
    if [ ! -f /usr/bin/docker-compose ]; then
      $MAYBE_SUDO ln -s /usr/local/bin/docker-compose /usr/bin/docker-compose
    fi
  fi

  if ! command_present docker-compose; then
    if [[ "$OSTYPE" == "darwin"* ]]; then
      error_exit "please install \`docker-compose\` manually" \
        "Usually, \`docker\` and \`docker-compose\` are bundled together, consider uninstalling your existing docker implementation" \
        "Instructions can be found at ${WHITE}${BOLD}https://docs.docker.com/${NORMAL}" \
        "${BOLD}Remember${NORMAL} to start the \`Docker\` app and wait for it to be ${GREEN}${BOLD}READY${NORMAL}."
    else
      error_exit "please install \`docker-compose\` manually" \
        "Usually, \`docker\` and \`docker-compose\` are bundled together, consider uninstalling your existing docker implementation" \
        "Instructions can be found at ${WHITE}${BOLD}https://docs.docker.com/${NORMAL}" \
        "${BOLD}Remember${NORMAL} to start the \`docker\` daemon/service and wait for it to be ${GREEN}${BOLD}READY${NORMAL}."
    fi
  fi
else
  # shellcheck disable=2016
  log_step '`docker-compose` found!'
fi

# if (! $MAYBE_SUDO docker stats --no-stream) && [ "$OSTYPE" == "linux-gnu" ] && [ "$DISTRO" != "*centos*" ]; then
#   sudo docker service start
# fi

# check if any running containers present

log_step "Checking for past recedues..."

if dronahq_containers_present; then
  log_step 'noticed you have tried DronaHQ before, cleaning up...'
  if [ -f ./dronahq.env ]; then
    $MAYBE_SUDO docker-compose rm -fsv
  fi
fi

if dronahq_trial_running; then
  log_step 'stopping DronaHQ for update...'
  $MAYBE_SUDO docker-compose down
fi

# cleaning directory

log_step "cleaning directory..."

if [ -f ./dronahq.env ]; then
  log_step 'found a partial install, cleaning it up...'
  mv dronahq.env dronahq.env.$(date +"%Y-%m-%d_%H-%M-%S")
fi

if [ -d "storage" ]; then
  log_step 'cleaning `storage`...'
  $MAYBE_SUDO mv storage storage-$(date +"%Y-%m-%d_%H-%M-%S")
fi

# generating environment

log_step "generating environment..."

ROOT_PASSWORD="idQnkrCOLNx5V05k8uPFZjpluOWF6PCO"
APPLICATION_PASSWORD="g76uCc7D9dUYGY6HGxWFmRhF64JayMpW"

if [ -f ./dronahq.env ]; then
  mv dronahq.env dronahq.env.$(date +"%Y-%m-%d_%H-%M-%S")
fi

echo "# DronaHQ Environment File" >dronahq.env
echo "" >>dronahq.env
echo "BUILDER_URL='http://localhost'" >>dronahq.env
echo "" >>dronahq.env
echo "MYSQL_USER='dronahq'" >>dronahq.env
echo "MYSQL_PASSWORD='$APPLICATION_PASSWORD'" >>dronahq.env
echo "MYSQL_DATABASE='db5x'" >>dronahq.env
echo "" >>dronahq.env
echo "MONGODB_USER='dronahq'" >>dronahq.env
echo "MONGODB_PASSWORD='$APPLICATION_PASSWORD'" >>dronahq.env
echo "MONGODB_DATABASE='db5x_studio'" >>dronahq.env
echo "" >>dronahq.env
echo "" >>dronahq.env
echo "# Variables required to create root credentials for database containers." >>dronahq.env
echo "MYSQL_ROOT_PASSWORD='$ROOT_PASSWORD'" >>dronahq.env
echo "MONGO_INITDB_ROOT_USERNAME='root'" >>dronahq.env
echo "MONGO_INITDB_ROOT_PASSWORD='$ROOT_PASSWORD'" >>dronahq.env
echo ""

read -p "Enter your DronaHQ License key. (Press Enter to skip) : " LICENSE_KEY

if [[ "$LICENSE_KEY" != "" ]]; then
  status=$(curl --insecure --silent --connect-timeout 8 --output /dev/null $DRONAHQ_LICENSE_URL/validate?key=$LICENSE_KEY -I -w "%{http_code}\n")
  if [[ "$status" != "202" ]]; then
    LICENSE_KEY=""
    log_warn "DronaHQ License Key you entered is invalid. We are proceeding with default key. you can configure it in 'dronahq.env' file later."
  fi
fi

echo "LICENSE_KEY='$LICENSE_KEY'" >>dronahq.env
echo "" >>dronahq.env

log_step 'downloading required resources...'

$MAYBE_SUDO docker-compose pull

# setting final steps

if [[ "$LICENSE_KEY" != "" ]]; then

  log_step "running DonaHQ! ${WHITE}${BOLD}This can take up to 5 minutes${NORMAL}"
  $MAYBE_SUDO docker-compose up -d

  echo ""
  echo " -- ${GREEN}${BOLD}!! DRONAHQ IS BOOTING !!${NORMAL} --"

  printf "%s%s%s%s" "Waiting for DronaHQ to start up... " "${RED}${BOLD}" "<Pressing Ctrl-C may prevent proper start-up>" "$NORMAL"

  sleep 10

  # NB: empty stuff to fully wipe out previous line completely
  printf "\r%s%s%s%s%s%s%s%s" "$MAGENTA" 'Check out your ' "$BOLD" 'BROWSER' "${NORMAL}${MAGENTA}" ' for some awesomeness!!!' "$NORMAL" '                              '
  echo

  # echo ""
  # echo "  ${CYAN}Navigate to${NORMAL}:          ${WHITE}${BOLD}http://localhost:3000/auth/signup${NORMAL}    or    ${WHITE}${BOLD}[publically_accessible_ip]:3000/auth/signup${NORMAL}"
  # echo "  ${CYAN}To STOP DronaHQ, run${NORMAL}:  ${WHITE}${BOLD}${DOCKER_CONTEXT}/stop-local-trial${NORMAL}"
  # echo "  ${CYAN}To RESTART DronaHQ, run${NORMAL}:  ${WHITE}${BOLD}${DOCKER_CONTEXT}/local-trial${NORMAL}"
  # echo ""

  echo "DronaHQ was installed in ${pwd}. It will run in the background until you manually stop it. If DronaHQ stops you can restart it without losing your data. "

  if command_present open; then
    open 'http://localhost'
  fi

else

  log_step "Hurray ! Your setup is done."
  echo ""
  echo "Now you can add your DronaHQ License Key in 'dronahq.env' file."
  echo ""
  echo "Then run following command to start DronaHQ."
  echo ""
  echo "'sudo docker-compose up -d'"
  echo ""
  echo "It can take upto 5 minutes to make your installation ready to use."
  echo ""
  
fi
