#!/bin/bash

function connect() {
  echo_h2 "Set Target OpenShift Cluster"

  PROMPT_FOR_LOGIN=false
  oc whoami &>> $LOGFILE
  if [[ $? == "0" ]]; then
    OCP_CONSOLE_ROUTE=$(oc -n openshift-console get route console -o=jsonpath='{.spec.host}')
    echo -e "Connected to OCP cluster: \n   ${COLOR_CYAN}${TEXT_UNDERLINE}https://$OCP_CONSOLE_ROUTE${TEXT_RESET}"
    echo "Connected to OCP cluster: https://$OCP_CONSOLE_ROUTE\n" >> $LOGFILE
    if [[ "$NO_CONFIRM" != true ]]; then
      if ! prompt_for_confirm_default_yes "Proceed with this cluster?"; then
        PROMPT_FOR_LOGIN=true
      fi
    fi
  else
    PROMPT_FOR_LOGIN=true
  fi

  if [[ $PROMPT_FOR_LOGIN == true ]]; then
    prompt_for_input "Server URL" OCP_LOGIN_URL
    prompt_for_secret "Login Token" OCP_LOGIN_TOKEN
    prompt_for_confirm "Disable TLS Verify?" OCP_DISABLE_TLS_VERIFY
    echo -ne "${TEXT_RESET}\033[1K"

    oc login --token=$OCP_LOGIN_TOKEN --server=$OCP_LOGIN_URL --insecure-skip-tls-verify=$OCP_DISABLE_TLS_VERIFY &>> $LOGFILE
    if [[ $? != "0" ]]; then
      echo_warning "Login to $OCP_LOGIN_URL failed"
      exit 1
    fi
    OCP_CONSOLE_ROUTE=$(oc -n openshift-console get route console -o=jsonpath='{.spec.host}')
    echo -e "Connected to OCP cluster: \n   ${COLOR_CYAN}${TEXT_UNDERLINE}https://$OCP_CONSOLE_ROUTE${TEXT_RESET}"
    echo "Connected to OCP cluster: https://$OCP_CONSOLE_ROUTE\n" >> $LOGFILE
    prompt_for_confirm "Proceed with installation on this cluster?" || exit 0
  fi
  ALREADY_CONFIRMED=true
  echo -ne "${TEXT_RESET}\033[1K"
}


function confirm_connection() {
  oc whoami &>> $LOGFILE
  if [[ $? == "0" ]]; then
    OCP_CONSOLE_ROUTE=$(oc -n openshift-console get route console -o=jsonpath='{.spec.host}')
    echo -e "Connected to OCP cluster: \n   ${COLOR_CYAN}${TEXT_UNDERLINE}https://$OCP_CONSOLE_ROUTE${TEXT_RESET}"
    echo "Connected to OCP cluster: https://$OCP_CONSOLE_ROUTE\n" >> $LOGFILE
  else
    echo_warning "You are not connected to an OCP cluster.  Run oc login, or use the CLI interactive mode."
    exit 1
  fi
}
