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

color() {
  return
}

SCRIPT_NAME="${BASH_SOURCE[0]:-unknown_script}"
catch_errors() {
  set -Euoe pipefail
  trap 'error_handler $LINENO "$BASH_COMMAND"' ERR
}

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

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

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
    echo 1>&2 -en "No Network! "
    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
  msg_ok "Set up Container OS"
  msg_ok "Network Connected: $(hostname -I)"
}

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() {
  msg_info "Updating Container OS"
  apt-get update
  apt-get -o Dpkg::Options::="--force-confold" -y dist-upgrade
  rm -rf /usr/lib/python3.*/EXTERNALLY-MANAGED
  msg_ok "Updated Container OS"
}

motd_ssh() {
  return
}

customize() {
   return
}