#!/bin/bash

export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:$PATH"
export TERM=xterm-256color
RED_TEXT_COLOR=`tput setaf 1`
GREEN_TEXT_COLOR=`tput setaf 2`
YELLOW_TEXT_COLOR=`tput setaf 3`
RESET_TEXT_COLOR=`tput sgr0`

isValidIPv4()
{
  local ip="$1"
  [[ "$ip" =~ ^([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$ ]] || return 1
  local a=${BASH_REMATCH[1]} b=${BASH_REMATCH[2]} c=${BASH_REMATCH[3]} d=${BASH_REMATCH[4]}
  (( a <= 255 && b <= 255 && c <= 255 && d <= 255 ))
}

isValidIPv6()
{
  local ip="$1"
  [[ -n "$ip" && "$ip" == *:* && "$ip" =~ ^[0-9a-fA-F:]+$ ]]
}

fetchUrl()
{
  curl -sk --connect-timeout 5 --max-time 10 --retry 3 --retry-delay 0 "$1" 2>/dev/null \
    | tr -d '[:space:]' || true
}

localIPv4()
{
  local ip
  ip=$(ip -4 -o route get 1.1.1.1 2>/dev/null \
       | awk '{for (i=1;i<=NF;i++) if ($i=="src") {print $(i+1); exit}}')
  if [ -z "$ip" ]; then
    ip=$(hostname -I 2>/dev/null | awk '{print $1}')
  fi
  printf '%s' "$ip"
}

localIPv6()
{
  ip -6 -o route get 2606:4700:4700::1111 2>/dev/null \
    | awk '{for (i=1;i<=NF;i++) if ($i=="src") {print $(i+1); exit}}'
}

resolveIp()
{
  local candidate

  candidate=$(fetchUrl https://d3qnd54q8gb3je.cloudfront.net/)
  if isValidIPv4 "$candidate"; then printf '%s' "$candidate"; return; fi

  candidate=$(fetchUrl https://api6.ipify.org/)
  if isValidIPv6 "$candidate"; then printf '%s' "$candidate"; return; fi

  candidate=$(localIPv4 || true)
  if isValidIPv4 "$candidate"; then printf '%s' "$candidate"; return; fi

  candidate=$(localIPv6 || true)
  if isValidIPv6 "$candidate"; then printf '%s' "$candidate"; return; fi
}

buildCloudPanelUrl()
{
  local ip host
  ip=$(resolveIp)
  host="$ip"
  [[ "$ip" == *:* ]] && host="[$ip]"
  printf 'https://%s:8443' "$host"
}

CLOUDPANEL_URL="$(buildCloudPanelUrl)"
if CUSTOM_CLP_DOMAIN=$(/usr/bin/clpctl app:config-value:get --key='custom_domain' --decrypt='0' 2>/dev/null) && [ -n "$CUSTOM_CLP_DOMAIN" ]; then
  CLOUDPANEL_URL="https://$CUSTOM_CLP_DOMAIN/"
fi

printf "\n${GREEN_TEXT_COLOR}"
printf "########################################################\n"
printf "###            Welcome to CloudPanel                 ###\n"
printf "########################################################${RESET_TEXT_COLOR}\n\n"

printf "* Website:         https://www.cloudpanel.io\n"
printf "* Documentation:   https://www.cloudpanel.io/docs/v3/\n"
printf "* Best Practices:  https://www.cloudpanel.io/docs/v3/best-practices/\n"

printf "* CloudPanel:     ${YELLOW_TEXT_COLOR} $CLOUDPANEL_URL ${RESET_TEXT_COLOR}\n"
printf "* CloudPanel CLI:  clpctl"

printf "\n\n"