#!/usr/bin/env bash
# Copyright (c) 2021-2026 community-scripts ORG
# Author: Michel Roegl-Brunner (michelroegl-brunner)
# License: MIT | https://github.com/community-scripts/ProxmoxVE/raw/main/LICENSE

color() {
  return
}

catch_errors() {
  set -Euo pipefail
  trap 'error_handler $LINENO "$BASH_COMMAND"' ERR
}

error_handler() {
  local line_number="$1"
  local command="$2"
  local error_message="Failure in line $line_number while executing command '$command'"   
  echo -e "\n$error_message\n" >&2
  exit 1
}

verb_ip6() {
  STD="silent"
  silent() {
    "$@" >/dev/null 2>&1 || error_handler "${BASH_LINENO[0]}" "$*"
  }
  return
}

msg_info() {
  local msg="$1"
  echo -ne "${msg}\n"
}

msg_ok() {
  local msg="$1"
  echo -e "${msg}\n"
}

msg_error() {

  local msg="$1"
  echo -e "${msg}\n"
}

RETRY_NUM=10
RETRY_EVERY=3
setting_up_container() {

  sed -i "/$LANG/ s/\(^# \)//" /etc/locale.gen
  locale_line=$(grep -v '^#' /etc/locale.gen | grep -E '^[a-zA-Z]' | awk '{print $1}' | head -n 1)
  echo "LANG=${locale_line}" >/etc/default/locale
  locale-gen >/dev/null
  export LANG=${locale_line}
  echo $tz >/etc/timezone
  ln -sf /usr/share/zoneinfo/$tz /etc/localtime

  for ((i = RETRY_NUM; i > 0; i--)); do
    if [ "$(hostname -I)" != "" ]; then
      break
    fi
    sleep $RETRY_EVERY
  done
  if [ "$(hostname -I)" = "" ]; then
    echo 1>&2 -e "\nNo Network After $RETRY_NUM Tries"
    echo -e "Check Network Settings"
    exit 101
  fi
  rm -rf /usr/lib/python3.*/EXTERNALLY-MANAGED
  systemctl disable -q --now systemd-networkd-wait-online.service
}

network_check() {
  RESOLVEDIP=$(getent hosts github.com | awk '{ print $1 }')
  if [[ -z "$RESOLVEDIP" ]]; then msg_error "DNS Lookup Failure"; else msg_ok "DNS Resolved github.com to $RESOLVEDIP"; fi
  set -e
}

update_os() {
  export DEBIAN_FRONTEND=noninteractive
  apt-get update >/dev/null 2>&1
  apt-get -o Dpkg::Options::="--force-confold" -y dist-upgrade >/dev/null
  rm -rf /usr/lib/python3.*/EXTERNALLY-MANAGED
}

motd_ssh() {
  return
}

customize() {
  return
}
