#!/usr/bin/env bash

# Migration workers intentionally isolate invocation state in subshells.
# ShellCheck otherwise links identically named function-local variables across
# those independent scopes and reports their isolation as lost assignments.
# shellcheck disable=SC2030,SC2031

# The most recent program version.
_VERSION="3.9.3"
_V="3.9"

# Bash version required
_bash_v=4

# The program full name
PROGRAM_NAME="Octojoom"

# Git Bash on Windows sets USERNAME but not USER
: "${USER:=${USERNAME:-$(id -un 2>/dev/null)}}"

# Set Server Hostname
SERVER_HOSTNAME="$(hostname)"

# Set the back title
BACK_TITLE="    Octoleo | ${USER}@${SERVER_HOSTNAME}"

# The SSH migration protocol must not run installers, initialize host settings,
# or emit interactive startup output. Load this installed script's own function
# definitions, then dispatch only the fixed worker operations below.
if [ "${1:-}" = --migration-worker ]; then
  set +x
  if (( BASH_VERSINFO[0] < 4 )); then
    printf '%s\n' 'Migration requires Bash 4 or newer.' >&2
    exit 1
  fi
  # shellcheck disable=SC1090
  source <(awk '/^(function )?[A-Za-z_][A-Za-z0-9_]*\(\) \{$/ {p=1} p {print} p && /^}$/ {p=0}' "${BASH_SOURCE[0]}")
  shift
  migrationWorker "$@"
  exit $?
fi

#####################################################################################################################VDM
######################################## The environment preparation
DOCKER_INSTALLED_THIS_SESSION=false
# make sure curl is installed
command -v curl >/dev/null 2>&1 || {
  echo >&2 "ERROR: ${PROGRAM_NAME} v${_VERSION} script require curl."
  echo >&2 "NOTICE: Please install curl first and then re-run this script again."
  exit 1
}
# Set OS number
OS_NUMBER=0 # Unknown
if [[ "$OSTYPE" == "linux-gnu"* ]]; then
  OS_NUMBER=1
elif [[ "$OSTYPE" == "darwin"* ]]; then
  OS_NUMBER=2
elif [[ "$OSTYPE" == "msys" || "$OSTYPE" == "cygwin" ]]; then
  OS_NUMBER=3
fi
# Check Bash version
function check_bash_version() {
  local bash_version="${1:-}"
  if [[ ! "$bash_version" =~ ^[0-9]+$ ]]; then
    echo >&2 "ERROR: Invalid required Bash version '${bash_version}'."
    return 1
  fi
  if (( BASH_VERSINFO[0] < 10#$bash_version )); then
    echo >&2 "ERROR: ${PROGRAM_NAME} v${_VERSION} script requires Bash version ${bash_version}.0 or above."
    return 1
  fi
}
# Check for the appropriate version of Bash
check_bash_version "$_bash_v" || exit 1

# Restrict new directories on Unix without mkdir's nonportable mode-setting
# behavior on Git Bash. Keep the caller's umask and mkdir's exit status intact.
function createPrivateDirectory() {
  (
    umask 077
    mkdir "$@"
  )
}

# Install whiptail with the host's package manager.
function install_whiptail_linux() {
  if command -v apt-get >/dev/null 2>&1; then
    sudo apt-get update || return 1
    sudo apt-get install whiptail -y || return 1
  elif command -v dnf >/dev/null 2>&1; then
    sudo dnf install -y newt || return 1
  elif command -v yum >/dev/null 2>&1; then
    sudo yum install -y newt || return 1
  elif command -v pacman >/dev/null 2>&1; then
    sudo pacman -S --needed --noconfirm libnewt || return 1
  elif command -v zypper >/dev/null 2>&1; then
    sudo zypper install -y newt || return 1
  else
    echo >&2 "ERROR: Unsupported package manager. Please install whiptail manually."
    return 1
  fi
  if ! command -v whiptail >/dev/null 2>&1; then
    echo >&2 "ERROR: Installation did not provide whiptail. Please install whiptail manually."
    return 1
  fi
}
# Install whiptail on macOS
function install_whiptail_macos() {
  if ! command -v brew >/dev/null 2>&1; then
    echo >&2 "ERROR: ${PROGRAM_NAME} v${_VERSION} script require Homebrew to install whiptail on macOS."
    echo >&2 "NOTICE: Please install Homebrew first and then re-run this script."
    exit 1
  fi
  brew install newt || return 1
  command -v whiptail >/dev/null 2>&1
}
# Install whiptail on Windows using Chocolatey
function install_whiptail_windows() {
  if ! command -v choco >/dev/null 2>&1; then
    echo >&2 "ERROR: ${PROGRAM_NAME} v${_VERSION} script require Chocolatey to install whiptail on Windows."
    echo >&2 "NOTICE: Please install Chocolatey first and then re-run this script."
    exit 1
  fi
  choco install newt --yes || return 1
  command -v whiptail >/dev/null 2>&1
}
# Main script
if ! command -v whiptail >/dev/null 2>&1; then
  echo "Whiptail is not installed. Do you want to install it now? (y/n)"
  read -r response
  if [[ "$response" =~ ^[Yy]$ ]]; then
    # If the user chooses Yes, install Docker based on the OS
    case "$OS_NUMBER" in
      1)
        install_whiptail_linux || exit 1
        ;;
      2)
        install_whiptail_macos || exit 1
        ;;
      3)
        install_whiptail_windows || exit 1
        ;;
      *)
        echo >&2 "ERROR: Unsupported operating system."
        exit 1
        ;;
    esac
  else
    echo >&2 "ERROR: ${PROGRAM_NAME} v${_VERSION} script require whiptail."
    echo >&2 "NOTICE: Please install whiptail first and then re-run this script again."
    exit 1
  fi
fi
# make sure awk is installed
command -v awk >/dev/null 2>&1 || {
  echo >&2 "ERROR: ${PROGRAM_NAME} v${_VERSION} script require awk."
  echo >&2 "NOTICE: Please install awk first and then re-run this script again."
  exit 1
}
# make sure rsync is installed (hmmm not always)
#command -v rsync >/dev/null 2>&1 || {
#  echo >&2 "ERROR: ${PROGRAM_NAME} v${_VERSION} script require rsync."
#  exit 1
#}
# Check and install Docker on Linux
function install_docker_linux() {
  echo "Installing Docker on Linux..."
  local ID='' ID_LIKE='' VERSION_CODENAME='' UBUNTU_CODENAME=''
  local DISTRO DISTRO_FAMILY REPO_DISTRO CODENAME architecture
  local -a conflicting_packages

  # Detect the distribution.
  if [ -f /etc/os-release ]; then
    # shellcheck source=/dev/null
    . /etc/os-release
    DISTRO="${ID}"
    # For derivatives (e.g., Linux Mint, Pop!_OS, Zorin), use the parent distro.
    if [ "${ID}" = fedora ]; then
      DISTRO_FAMILY="fedora"
    elif [ -n "${ID_LIKE}" ]; then
      case "${ID_LIKE}" in
        *debian*|*ubuntu*) DISTRO_FAMILY="debian" ;;
        *fedora*|*rhel*)   DISTRO_FAMILY="rhel" ;;
        *suse*)            DISTRO_FAMILY="suse" ;;
        *)                 DISTRO_FAMILY="${ID_LIKE}" ;;
      esac
    else
      case "${DISTRO}" in
        ubuntu|debian)          DISTRO_FAMILY="debian" ;;
        fedora)                 DISTRO_FAMILY="fedora" ;;
        centos|rhel|rocky|alma|almalinux) DISTRO_FAMILY="rhel" ;;
        opensuse*|sles)         DISTRO_FAMILY="suse" ;;
        *)                      DISTRO_FAMILY="" ;;
      esac
    fi
  else
    echo >&2 "ERROR: Cannot detect Linux distribution. /etc/os-release not found."
    exit 1
  fi

  # Resolve derivative repositories before making any system changes.
  if [ "$DISTRO_FAMILY" = debian ]; then
    REPO_DISTRO=debian
    if [ "$DISTRO" = ubuntu ] || [[ " $ID_LIKE " == *" ubuntu "* ]] || [ -n "$UBUNTU_CODENAME" ]; then
      REPO_DISTRO=ubuntu
    fi
    CODENAME="${UBUNTU_CODENAME:-$VERSION_CODENAME}"
    if [[ ! "$CODENAME" =~ ^[a-z][a-z0-9]*$ ]]; then
      echo >&2 "ERROR: Cannot determine the parent distribution codename. Please install Docker manually."
      return 1
    fi
    architecture=$(dpkg --print-architecture) || return 1
    [ -n "$architecture" ] || return 1
  elif [[ "$DISTRO_FAMILY" != fedora && "$DISTRO_FAMILY" != rhel ]]; then
    echo >&2 "ERROR: Unsupported Linux distribution '${DISTRO}' (family: '${DISTRO_FAMILY}')."
    echo >&2 "Please install Docker manually: https://docs.docker.com/engine/install/"
    return 1
  fi

  # Remove any conflicting/unofficial Docker packages.
  echo "Removing any conflicting Docker packages..."
  case "${DISTRO_FAMILY}" in
    debian)
      # shellcheck disable=SC2086
      for pkg in docker.io docker-doc docker-compose docker-compose-v2 docker-buildx podman-docker containerd runc; do
        sudo apt-get remove -y "$pkg" 2>/dev/null || true
      done
      ;;
    fedora|rhel)
      conflicting_packages=(docker docker-client docker-client-latest docker-common
        docker-latest docker-latest-logrotate docker-logrotate docker-engine podman-docker)
      if [ "$DISTRO_FAMILY" = fedora ]; then
        conflicting_packages+=(docker-selinux docker-engine-selinux)
      else
        conflicting_packages+=(podman runc)
      fi
      for pkg in "${conflicting_packages[@]}"; do
        sudo dnf remove -y "$pkg" 2>/dev/null || sudo yum remove -y "$pkg" 2>/dev/null || true
      done
      ;;
  esac

  # Install Docker based on the distribution family.
  case "${DISTRO_FAMILY}" in
    debian)
      # Install prerequisites.
      sudo apt-get update || return 1
      sudo apt-get install -y ca-certificates curl gnupg || return 1

      # Set up the official Docker GPG key.
      sudo install -m 0755 -d /etc/apt/keyrings || return 1
      (set -o pipefail
        curl -fsSL "https://download.docker.com/linux/${REPO_DISTRO}/gpg" | \
          sudo gpg --batch --yes --dearmor -o /etc/apt/keyrings/docker.gpg
      ) || return 1
      sudo chmod a+r /etc/apt/keyrings/docker.gpg || return 1

      echo "deb [arch=${architecture} signed-by=/etc/apt/keyrings/docker.gpg] \
        https://download.docker.com/linux/${REPO_DISTRO} ${CODENAME} stable" | \
        sudo tee /etc/apt/sources.list.d/docker.list > /dev/null || return 1

      # Install Docker Engine, CLI, containerd, and Compose plugin.
      sudo apt-get update || return 1
      sudo apt-get install -y docker-ce docker-ce-cli containerd.io \
        docker-buildx-plugin docker-compose-plugin || return 1
      ;;

    fedora)
      # Install prerequisites.
      sudo dnf install -y dnf-plugins-core || return 1

      # Add the Docker repository.
      sudo dnf config-manager addrepo --from-repofile \
        https://download.docker.com/linux/fedora/docker-ce.repo || \
        sudo dnf config-manager --add-repo https://download.docker.com/linux/fedora/docker-ce.repo || return 1

      # Install Docker Engine, CLI, containerd, and Compose plugin.
      sudo dnf install -y docker-ce docker-ce-cli containerd.io \
        docker-buildx-plugin docker-compose-plugin || return 1
      ;;

    rhel)
      # Works for CentOS, RHEL, Rocky Linux, AlmaLinux.
      REPO_DISTRO=centos
      [ "$DISTRO" != rhel ] || REPO_DISTRO=rhel
      if command -v dnf &>/dev/null; then
        sudo dnf install -y dnf-plugins-core || return 1
        sudo dnf config-manager --add-repo \
          "https://download.docker.com/linux/${REPO_DISTRO}/docker-ce.repo" || return 1
        sudo dnf install -y docker-ce docker-ce-cli containerd.io \
          docker-buildx-plugin docker-compose-plugin || return 1
      else
        sudo yum install -y yum-utils || return 1
        sudo yum-config-manager --add-repo \
          https://download.docker.com/linux/centos/docker-ce.repo || return 1
        sudo yum install -y docker-ce docker-ce-cli containerd.io \
          docker-buildx-plugin docker-compose-plugin || return 1
      fi
      ;;

    *)
      echo >&2 "ERROR: Unsupported Linux distribution '${DISTRO}' (family: '${DISTRO_FAMILY}')."
      echo >&2 "Please install Docker manually: https://docs.docker.com/engine/install/"
      exit 1
      ;;
  esac

  # Create the docker group (may already exist).
  getent group docker >/dev/null 2>&1 || sudo groupadd docker || return 1

  # Add the current user to the docker group.
  sudo usermod -aG docker "$USER" || return 1

  # Enable and start the Docker service.
  sudo systemctl enable docker.service || return 1
  sudo systemctl start docker.service || return 1
  sudo systemctl enable containerd.service || return 1
  sudo systemctl start containerd.service || return 1

  docker --version || return 1
  docker compose version || return 1

  DOCKER_INSTALLED_THIS_SESSION=true
  echo "Docker is installed."
}
# Check and install Docker on macOS
function install_docker_macos() {
  echo "Installing Docker on macOS..."
  # Check if Homebrew is installed.
  if ! command -v brew &>/dev/null; then
    echo "Homebrew is not installed. Installing Homebrew first..."
    local brew_installer
    brew_installer=$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh) || return 1
    [ -n "$brew_installer" ] || return 1
    /bin/bash -c "$brew_installer" || return 1
    # Add Homebrew to PATH for Apple Silicon Macs (default install location changed).
    if [[ -f /opt/homebrew/bin/brew ]]; then
      eval "$(/opt/homebrew/bin/brew shellenv)"
    elif [[ -f /usr/local/bin/brew ]]; then
      eval "$(/usr/local/bin/brew shellenv)"
    fi
    if ! command -v brew &>/dev/null; then
      echo >&2 "ERROR: Homebrew installation failed. Please install it manually:"
      echo >&2 "https://brew.sh"
      exit 1
    fi
  fi
  # Check if Docker Desktop is already installed but just not in PATH.
  if [[ -d "/Applications/Docker.app" ]]; then
    echo "Docker Desktop is already installed but Docker CLI is not available."
    echo "Starting Docker Desktop..."
    open /Applications/Docker.app || return 1
    echo "Please wait for Docker Desktop to finish starting, then re-run this script."
    exit 0
  fi
  # Install Docker Desktop via Homebrew.
  brew install --cask docker || return 1
  # Start Docker Desktop.
  open /Applications/Docker.app || return 1
  # Wait for Docker daemon to become available.
  echo "Waiting for Docker Desktop to start..."
  local TIMEOUT=120 ELAPSED=0
  while ! docker info &>/dev/null; do
    if [[ ${ELAPSED} -ge ${TIMEOUT} ]]; then
      echo >&2 "WARNING: Docker Desktop did not start within ${TIMEOUT} seconds."
      echo >&2 "Please finish setup manually, then re-run this script."
      exit 1
    fi
    sleep 2
    ELAPSED=$((ELAPSED + 2))
    printf "."
  done
  echo ""
  docker --version || return 1
  docker compose version || return 1
  # macOS does not require a Docker group login refresh.
  echo "Docker is installed and running."
}
# Check and install Docker on Windows (MSYS/Cygwin)
function install_docker_windows() {
  echo "Please download and install Docker Desktop from https://www.docker.com/products/docker-desktop"
  echo "Docker Desktop is required for Windows environments."
  exit 0
}
# Check if Docker is installed
if ! command -v docker &>/dev/null; then
  # If Docker is not installed, ask the user if they want to install it
  if whiptail --yesno "Docker is not installed. Do you want to install it now?" \
      --backtitle "${BACK_TITLE}" 10 60; then
    # If the user chooses Yes, install Docker based on the OS
    case "$OS_NUMBER" in
      1)
        install_docker_linux || exit 1
        ;;
      2)
        install_docker_macos || exit 1
        ;;
      3)
        install_docker_windows
        ;;
      *)
        echo >&2 "ERROR: Unsupported operating system."
        exit 1
        ;;
    esac
  else
    # If the user chooses No, exit the script with an error message
    echo >&2 "ERROR: ${PROGRAM_NAME} v${_VERSION} script requires Docker."
    echo >&2 "NOTICE: Please install Docker first and then re-run this script again."
    exit 1
  fi
fi
# Install Docker Compose V2 plugin on Linux (via package manager)
function install_docker_compose_linux() {
  echo "Installing Docker Compose plugin on Linux..."
  # The official Docker repo (which should already be configured if Docker is installed)
  # provides the Compose plugin as a package.
  if command -v apt-get &>/dev/null; then
    sudo apt-get update || return 1
    sudo apt-get install -y docker-compose-plugin || return 1
  elif command -v dnf &>/dev/null; then
    sudo dnf install -y docker-compose-plugin || return 1
  elif command -v yum &>/dev/null; then
    sudo yum install -y docker-compose-plugin || return 1
  else
    echo >&2 "ERROR: Could not detect a supported package manager (apt, dnf, yum)."
    echo >&2 "Please install docker-compose-plugin manually."
    exit 1
  fi
  docker compose version || return 1
  echo "Docker Compose plugin is installed."
}
# Install Docker Compose V2 plugin on macOS
function install_docker_compose_macos() {
  echo "Installing Docker Compose plugin on macOS..."
  # Docker Desktop for macOS includes Compose V2 by default.
  # If Docker Desktop is installed, the plugin should already be available.
  if docker compose version &>/dev/null; then
    echo "Docker Compose plugin is already available via Docker Desktop."
    docker compose version
    return 0
  fi
  # If not available (e.g., Docker installed via Homebrew without Desktop), install manually.
  local plugin_dir="$HOME/.docker/cli-plugins" release COMPOSE_VERSION download
  release=$(curl -fsSL https://api.github.com/repos/docker/compose/releases/latest) || return 1
  COMPOSE_VERSION=$(printf '%s\n' "$release" | sed -nE 's/.*"tag_name"[[:space:]]*:[[:space:]]*"(v[0-9]+\.[0-9]+\.[0-9]+)".*/\1/p' | head -n 1)
  if [ -z "$COMPOSE_VERSION" ]; then
    echo >&2 "ERROR: Could not determine the Docker Compose release version."
    return 1
  fi
  mkdir -p "$plugin_dir" || return 1
  download=$(mktemp "$plugin_dir/.docker-compose.XXXXXX") || return 1
  if ! curl -fsSL "https://github.com/docker/compose/releases/download/${COMPOSE_VERSION}/docker-compose-$(uname -s)-$(uname -m)" \
      -o "$download" || ! [ -s "$download" ] || ! chmod +x "$download" || ! "$download" version; then
    rm -f "$download"
    echo >&2 "ERROR: Docker Compose download or validation failed."
    return 1
  fi
  if ! mv -f "$download" "$plugin_dir/docker-compose"; then
    rm -f "$download"
    return 1
  fi
  echo "Docker Compose plugin ${COMPOSE_VERSION} is installed."
}
# Install Docker Compose on Windows (MSYS/Cygwin)
function install_docker_compose_windows() {
  echo "Docker Desktop for Windows includes Docker Compose V2 by default."
  echo "Please install or update Docker Desktop from https://www.docker.com/products/docker-desktop/"
  echo "After installation, 'docker compose' will be available."
  exit 0
}
# Check if Docker Compose is installed
if ! docker compose version &>/dev/null; then
  # If Docker Compose is not installed, ask the user if they want to install it
  if whiptail --yesno "Docker Compose is not installed. Do you want to install it now?" \
        --backtitle "${BACK_TITLE}" 10 60; then
    # If the user chooses Yes, install Docker Compose based on the OS
    case "$OS_NUMBER" in
      1)
        install_docker_compose_linux || exit 1
        ;;
      2)
        install_docker_compose_macos || exit 1
        ;;
      3)
        install_docker_compose_windows
        ;;
      *)
        echo >&2 "ERROR: Unsupported operating system."
        exit 1
        ;;
    esac
  else
    # If the user chooses No, exit the script with an error message
    echo >&2 "ERROR: ${PROGRAM_NAME} v${_VERSION} script requires docker-compose."
    echo >&2 "NOTICE: Please install docker compose first and then re-run this script again."
    exit 1
  fi
fi
# fix user permissions on Docker install
if [ "$DOCKER_INSTALLED_THIS_SESSION" = true ]; then
  whiptail --title "NOTICE | ${PROGRAM_NAME} v${_V}" --backtitle "${BACK_TITLE}" \
      --msgbox "Docker has been successfully installed and your user was added to the required Docker group.\n\nHowever, your current terminal session is still using your OLD permissions. This is normal on Linux.\n\nTo activate your new Docker permissions, you MUST:\n\n  1. Log out of your user account completely\n  2. Log back in again (or reboot)\n\nAfter logging back in, you can run this ${PROGRAM_NAME} script again and Docker will work correctly.\n\nThis step is required only once." 20 112
	exit 0
fi
# Setting the LC_ALL with respect to language, regional settings, to use POSIX locale,
# so ASCII character set and standardizes behavior is used for consistent across different environments
export LC_ALL=C
# just clear the screen
clear

#####################################################################################################################VDM
######################################## The main method
function main() {
  # we check if we have a type and a task
  # we use the __TRuST__ convention AS "PUBLIC METHODS" to avoid wrong calls, and hide other functions
  if [ ${#VDM_CONTAINER_TYPE} -ge 1 ] && [ ${#VDM_TASK} -ge 1 ] && isFunc "${VDM_CONTAINER_TYPE}__TRuST__${VDM_TASK}"; then
    "${VDM_CONTAINER_TYPE}__TRuST__${VDM_TASK}"
  elif [ -n "${VDM_CONTAINER_TYPE}" ] || [ -n "${VDM_TASK}" ]; then
    echo >&2 "ERROR: Unsupported container type or task: ${VDM_CONTAINER_TYPE:-<missing type>}/${VDM_TASK:-<missing task>}."
    return 17
  else
    mainMenu
  fi
}

#####################################################################################################################VDM
######################################## SETUP TRAEFIK
function traefik__TRuST__setup() {
  # load this container type globals
  # shellcheck disable=SC1090
  if [ -f "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/.env" ]; then
    loadEnvFile "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/.env" || return 1
  fi
  # check if we have secure switch set
  setSecureState
  # removed cloudflare features by default
  VDM_REMOVE_CLOUDFLARE_SERVICE="#"
  # setup letsencrypt stuff
  VDM_REMOVE_SECURE=''
  VDM_HTTP_SCHEME="https"
  if $VDM_SECURE; then
    setSecureCloudflareState "traefik"
    # get the email if not set
    while [ ${#VDM_SECURE_EMAIL} -le 1 ]; do
      # get the value
      VDM_SECURE_EMAIL=$(getInput 'Enter email for the Letsencrypt setup.' '' 'Enter Valid Email') || return $?
      # keep asking
      [ ${#VDM_SECURE_EMAIL} -ge 1 ] || {
        showError "You must enter an email for the Letsencrypt setup."
      }
    done
    setContainerEnvVariable "VDM_SECURE_EMAIL=\"${VDM_SECURE_EMAIL}\"" || return $?
    if $VDM_SECURE_CLOUDFLARE; then
      VDM_REMOVE_CLOUDFLARE_SERVICE=''
      # get the api token if not set
      while [ ${#VDM_CLOUDFLARE_DNS_API_TOKEN} -le 1 ]; do
        # get the value
        VDM_CLOUDFLARE_DNS_API_TOKEN=$(getInput 'Enter your Cloudflare API token that has Zone:DNS:Edit permission used with API DNS lookup for the auto-resolver in the ACME.' '' 'Enter Valid Email') || return $?
        # keep asking
        [ ${#VDM_CLOUDFLARE_DNS_API_TOKEN} -ge 1 ] || {
          showError "You must enter your Cloudflare API token that has Zone:DNS:Edit permission used with API DNS lookup for the auto-resolver in the ACME."
        }
      done
      setContainerEnvVariable "VDM_CLOUDFLARE_DNS_API_TOKEN=\"${VDM_CLOUDFLARE_DNS_API_TOKEN}\"" || return $?
    fi
    # make sure the directory exist
    mkdir -p "${VDM_PROJECT_PATH}/traefik" || return 1
    # Preserve certificates and account keys when setup is run again.
    local acme_file
    for acme_file in acme.json acme-cloudflare.json; do
      if [ ! -e "${VDM_PROJECT_PATH}/traefik/${acme_file}" ]; then
        printf '{}\n' >"${VDM_PROJECT_PATH}/traefik/${acme_file}" || return 1
      elif [ ! -f "${VDM_PROJECT_PATH}/traefik/${acme_file}" ]; then
        showError "The ACME storage (${acme_file}) must be a file."
        return 1
      fi
      sudo chmod 600 "${VDM_PROJECT_PATH}/traefik/${acme_file}" || return 1
    done
    # and is owned by root
    sudo chown -R 0:0 "${VDM_PROJECT_PATH}/traefik" || return 1
  else
    VDM_REMOVE_SECURE="#"
    VDM_HTTP_SCHEME="http"
  fi
  # set the main domain if not set
  setMainDomain || return $?
  ##########################
  ### export all we need
  # global
  export VDM_CONTAINER_TYPE
  export VDM_REPO_PATH
  export VDM_PROJECT_PATH
  # container
  export VDM_REMOVE_SECURE
  export VDM_HTTP_SCHEME
  saveContainerCompose traefikContainer "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/docker-compose.yml" || return 1
  # saved the file
  showNotice "Saved ${VDM_CONTAINER_TYPE}:docker-compose.yml file.\nSetup of this container is complete!"
  # ask if we should continue to enable
  if getInputYesNo "Would you also like to enable this ${VDM_CONTAINER_TYPE^} container" \
    "Enable Container" 8 112 "defaultno"; then
    enableContainer "${VDM_CONTAINER_TYPE}" || return $?
  fi
  ##########################
  ### unset all no longer needed
  # container
  unset VDM_REMOVE_SECURE
  unset VDM_HTTP_SCHEME
  # return a success
  return 0
}

# Return the Traefik Container setup YAML
function traefikContainer() {
  cat <<EOF
services:
  traefik:
    container_name: traefik
    image: "traefik:latest"
${VDM_REMOVE_CLOUDFLARE_SERVICE}    environment:
${VDM_REMOVE_CLOUDFLARE_SERVICE}      - CLOUDFLARE_DNS_API_TOKEN=\${VDM_CLOUDFLARE_DNS_API_TOKEN:-}
    command:
      # Entrypoints
      - --entrypoints.web.address=:80
      - --entrypoints.websecure.address=:443
#      - --api.dashboard=true
#      - --api.insecure=true

      # Forwarded headers are trusted only from explicitly configured proxies.
#      - --entrypoints.web.forwardedheaders.trustedips=192.0.2.0/24
#      - --entrypoints.websecure.forwardedheaders.trustedips=192.0.2.0/24

      # Providers
      - --providers.docker=true
      - --providers.docker.exposedbydefault=false
      - --providers.file.directory=/conf
      - --providers.file.watch=true

      # Logging
      - --log.level=INFO
      - --accesslog=true
      - --accesslog.filepath=/logs/access.log

      # ACME - HTTP resolver for non-Cloudflare domains
${VDM_REMOVE_SECURE}      - --certificatesresolvers.vdmresolver.acme.httpchallenge=true
${VDM_REMOVE_SECURE}      - --certificatesresolvers.vdmresolver.acme.httpchallenge.entrypoint=web
${VDM_REMOVE_SECURE}      - --certificatesresolvers.vdmresolver.acme.email=\${VDM_SECURE_EMAIL:-user@demo.com}
${VDM_REMOVE_SECURE}      - --certificatesresolvers.vdmresolver.acme.storage=/acme.json
${VDM_REMOVE_SECURE}      - --certificatesresolvers.vdmresolver.acme.keytype=RSA4096

      # ACME - DNS resolver for Cloudflare-proxied domains
${VDM_REMOVE_CLOUDFLARE_SERVICE}      - --certificatesresolvers.cfresolver.acme.dnschallenge.provider=cloudflare
${VDM_REMOVE_CLOUDFLARE_SERVICE}      - --certificatesresolvers.cfresolver.acme.email=\${VDM_SECURE_EMAIL:-user@demo.com}
${VDM_REMOVE_CLOUDFLARE_SERVICE}      - --certificatesresolvers.cfresolver.acme.storage=/acme-cloudflare.json
${VDM_REMOVE_CLOUDFLARE_SERVICE}      - --certificatesresolvers.cfresolver.acme.keytype=RSA4096

    restart: unless-stopped

    ports:
      - "80:80"
      - "443:443"

    volumes:
      - /var/run/docker.sock:/var/run/docker.sock:ro
      - "\${VDM_PROJECT_PATH}/traefik/logs:/logs"
      - "\${VDM_PROJECT_PATH}/traefik/errors:/errors"
      - "\${VDM_PROJECT_PATH}/traefik/conf:/conf"
${VDM_REMOVE_SECURE}      - "\${VDM_PROJECT_PATH}/traefik/acme.json:/acme.json"
${VDM_REMOVE_SECURE}      - "\${VDM_PROJECT_PATH}/traefik/acme-cloudflare.json:/acme-cloudflare.json"

    labels:
      - "traefik.enable=true"

      # Global HTTP -> HTTPS redirect
${VDM_REMOVE_SECURE}      - "traefik.http.routers.http-catchall.rule=HostRegexp(\`.+\`)"
${VDM_REMOVE_SECURE}      - "traefik.http.routers.http-catchall.entrypoints=web"
${VDM_REMOVE_SECURE}      - "traefik.http.routers.http-catchall.middlewares=redirect-https"
${VDM_REMOVE_SECURE}      - "traefik.http.middlewares.redirect-https.redirectscheme.scheme=https"
${VDM_REMOVE_SECURE}      - "traefik.http.middlewares.redirect-https.redirectscheme.permanent=true"

      # Security headers
      - "traefik.http.middlewares.joomla-security.headers.stsSeconds=63072000"
      - "traefik.http.middlewares.joomla-security.headers.stsIncludeSubdomains=true"
      - "traefik.http.middlewares.joomla-security.headers.stsPreload=true"
      - "traefik.http.middlewares.joomla-security.headers.browserXssFilter=true"
      - "traefik.http.middlewares.joomla-security.headers.contentTypeNosniff=true"
#      - "traefik.http.middlewares.joomla-security.headers.referrerPolicy=same-origin"

      # Cloudflare middleware
${VDM_REMOVE_CLOUDFLARE_SERVICE}      - "traefik.http.middlewares.cloudflare.headers.customrequestheaders.X-Forwarded-Proto=https"

    networks:
      - traefik

networks:
  traefik:
    external: true
    name: ${VDM_TRAEFIK_GATEWAY:-traefik_webgateway}
EOF
}

#####################################################################################################################VDM
######################################## SETUP PORTAINER
function portainer__TRuST__setup() {
  # load this container type globals
  # shellcheck disable=SC1090
  if [ -f "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/.env" ]; then
    loadEnvFile "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/.env" || return 1
  fi
  # check if we have secure switch set
  setSecureState
  # setup letsencrypt stuff
  VDM_PORT_SECURE_LABELS=''
  VDM_REMOVE_SECURE=''
  VDM_ENTRY_POINT="websecure"
  VDM_CERT_RESOLVER="vdmresolver"
  if $VDM_SECURE; then
    VDM_PORT_SECURE_LABELS+=$(getYMLine3 "- \"traefik.http.routers.portainer.entrypoints=${VDM_ENTRY_POINT}\"")
    setSecureCloudflareState "portainer"
    if $VDM_SECURE_CLOUDFLARE; then
      VDM_CERT_RESOLVER="cfresolver"
    fi
    VDM_PORT_SECURE_LABELS+=$(getYMLine3 "- \"traefik.http.routers.portainer.tls.certresolver=${VDM_CERT_RESOLVER}\"")
  else
    VDM_REMOVE_SECURE="#"
    VDM_ENTRY_POINT="web"
  fi
  # set the domain
  setDomain || return $?
  # get the sub domain if not set
  setSubDomain 'port' '' 'joomla' || return $?
  ##########################
  ### export all we need
  # global
  export VDM_CONTAINER_TYPE
  export VDM_REPO_PATH
  export VDM_PROJECT_PATH
  # container
  export VDM_REMOVE_SECURE
  export VDM_ENTRY_POINT
  export VDM_PORT_SECURE_LABELS
  export VDM_CERT_RESOLVER
  # set host file if needed
  updateHostFile
  saveContainerCompose portainerContainer "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/docker-compose.yml" || return 1
  # saved the file
  showNotice "Saved ${VDM_CONTAINER_TYPE}:docker-compose.yml file.\nSetup of this container is complete!"
  # ask if we should continue to enable
  if getInputYesNo "Would you also like to enable this ${VDM_CONTAINER_TYPE^} container" \
    "Enable Container" 8 112 "defaultno"; then
    enableContainer "${VDM_CONTAINER_TYPE}" || return $?
  fi
  ##########################
  ### unset all no longer needed
  # container
  unset VDM_SUBDOMAIN
  unset VDM_REMOVE_SECURE
  unset VDM_ENTRY_POINT
  unset VDM_PORT_SECURE_LABELS
  unset VDM_CERT_RESOLVER
  # return a success
  return 0
}

# return the Portainer Container setup yml
function portainerContainer() {
  # we build the yml file
  cat <<EOF
services:
  portainer:
    image: portainer/portainer-ce:latest
    container_name: portainer
    command: -H unix:///var/run/docker.sock
    restart: always
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock
      - portainer_data:/data
    labels:
      # Frontend
      - "traefik.enable=true"
      - "traefik.http.routers.portainer.rule=Host(\`${VDM_SUBDOMAIN}.${VDM_DOMAIN}\`)"${VDM_PORT_SECURE_LABELS}
      - "traefik.http.routers.portainer.service=portainer"
      - "traefik.http.services.portainer.loadbalancer.server.port=9000"

      # Edge
#      - "traefik.http.routers.portaineredge.rule=Host(\`${VDM_SUBDOMAIN}edge.${VDM_DOMAIN}\`)"
#      - "traefik.http.routers.portaineredge.entrypoints=${VDM_ENTRY_POINT}"
#      - "traefik.http.routers.portaineredge.tls.certresolver=${VDM_CERT_RESOLVER}"
#      - "traefik.http.routers.portaineredge.service=portaineredge"
#      - "traefik.http.services.portaineredge.loadbalancer.server.port=8000"
    networks:
      - traefik

volumes:
  portainer_data:

networks:
  traefik:
    external: true
    name: ${VDM_TRAEFIK_GATEWAY:-traefik_webgateway}
EOF
}

#####################################################################################################################VDM
######################################## SETUP JOOMLA
function joomla__TRuST__setup() {
  # load this container type globals
  # shellcheck disable=SC1090
  if [ -f "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/.env" ]; then
    loadEnvFile "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/.env" || return 1
  fi
  # we need to pull these values from the env if set
  local vdm_key_db
  local vdm_env_db
  local vdm_key_user
  local vdm_env_user
  local vdm_key_pass
  local vdm_env_pass
  local vdm_key_root
  local vdm_env_root
  local vdm_middlewares
  # get the Joomla image source
  setImageSource || return $?
  # get the key if not set
  setUniqueKey || return $?
  # get the env key if not set
  setEnvironmentKey || return $?
  # set the domain
  setDomain || return $?
  # get the sub domain if not set TODO get dynamic joomla domain name
  setSubDomain "${VDM_KEY,,}" "joomla" || return $?
  # check if we have secure switch set
  setSecureState
  # setup letsencrypt stuff
  VDM_JOOMLA_SECURE_LABELS=''
  VDM_PHPMYADMIN_SECURE_LABELS=''
  VDM_REMOVE_SECURE=''
  VDM_ENTRY_POINT="websecure"
  VDM_HTTP_SCHEME="https://"
  VDM_CERT_RESOLVER="vdmresolver"
  if $VDM_SECURE; then
    setSecureCloudflareState "joomla"
    if $VDM_SECURE_CLOUDFLARE; then
      VDM_CERT_RESOLVER="cfresolver"
    fi
    VDM_JOOMLA_SECURE_LABELS+=$(getYMLine3 "- \"traefik.http.routers.joomla${VDM_KEY}.entrypoints=${VDM_ENTRY_POINT}\"")
    VDM_JOOMLA_SECURE_LABELS+=$(getYMLine3 "- \"traefik.http.routers.joomla${VDM_KEY}.tls.certresolver=${VDM_CERT_RESOLVER}\"")
    VDM_JOOMLA_SECURE_LABELS+=$(getYMLine3 "- \"traefik.http.routers.joomla${VDM_KEY}.service=joomla${VDM_KEY}\"")
    # add enterprise middlewares (Security and Cloudflare)
    vdm_middlewares="joomla-security"
    if $VDM_SECURE_CLOUDFLARE; then
      vdm_middlewares="cloudflare,joomla-security"
    fi
    VDM_JOOMLA_SECURE_LABELS+=$(getYMLine3 "- \"traefik.http.routers.joomla${VDM_KEY}.middlewares=${vdm_middlewares}\"")
    VDM_JOOMLA_SECURE_LABELS+=$(getYMLine3 "- \"traefik.http.services.joomla${VDM_KEY}.loadbalancer.server.port=80\"")
    # add phpmyadmin labels
    VDM_PHPMYADMIN_SECURE_LABELS+=$(getYMLine3 "- \"traefik.http.routers.phpmyadmin${VDM_KEY}.entrypoints=${VDM_ENTRY_POINT}\"")
    VDM_PHPMYADMIN_SECURE_LABELS+=$(getYMLine3 "- \"traefik.http.routers.phpmyadmin${VDM_KEY}.tls.certresolver=${VDM_CERT_RESOLVER}\"")
    VDM_PHPMYADMIN_SECURE_LABELS+=$(getYMLine3 "- \"traefik.http.routers.phpmyadmin${VDM_KEY}.service=phpmyadmin${VDM_KEY}\"")
    VDM_PHPMYADMIN_SECURE_LABELS+=$(getYMLine3 "- \"traefik.http.routers.phpmyadmin${VDM_KEY}.middlewares=${vdm_middlewares}\"")
    VDM_PHPMYADMIN_SECURE_LABELS+=$(getYMLine3 "- \"traefik.http.services.phpmyadmin${VDM_KEY}.loadbalancer.server.port=80\"")
  else
    VDM_REMOVE_SECURE="#"
    VDM_ENTRY_POINT="web"
    VDM_HTTP_SCHEME="http://"
  fi
  # set the details
  vdm_key_db="VDM_${VDM_ENV_KEY^^}_DB"
  vdm_env_db="${!vdm_key_db}"
  vdm_key_user="VDM_${VDM_ENV_KEY^^}_DB_USER"
  vdm_env_user="${!vdm_key_user}"
  vdm_key_pass="VDM_${VDM_ENV_KEY^^}_DB_PASS"
  vdm_env_pass="${!vdm_key_pass}"
  vdm_key_root="VDM_${VDM_ENV_KEY^^}_DB_ROOT"
  vdm_env_root="${!vdm_key_root}"
  # now we check if its has been set
  vdm_database_name="${vdm_database_name:-$vdm_env_db}"
  vdm_database_user="${vdm_database_user:-$vdm_env_user}"
  vdm_database_pass="${vdm_database_pass:-$vdm_env_pass}"
  vdm_database_rootpass="${vdm_database_rootpass:-$vdm_env_root}"
  # check if env is already set
  # shellcheck disable=SC2015
  [ -f "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/.env" ] && grep -q "VDM_${VDM_ENV_KEY^^}_DB=" "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/.env" || {
    # add a space or create the file
    [ -f "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/.env" ] && echo '' >>"${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/.env"
    # get the database name needed
    while [ ${#vdm_database_name} -le 1 ]; do
      # get the value
      vdm_database_name=$(getInput "Enter Database Name\n[Text with no spaces that is only underscore and alphabetical]" \
        "vdm_io" 'Enter Database Name') || return $?
      # keep asking if empty or does exist
      [ ${#vdm_database_name} -ge 1 ] || {
        showError "You must enter a database name!"
      }
    done
    # get the database user name needed
    while [ ${#vdm_database_user} -le 1 ]; do
      # get the value
      vdm_database_user=$(getInput "Enter Database Username\n[Text with no spaces that is only underscore and alphabetical]" \
        "vdm_user" 'Enter Database Username') || return $?
      # keep asking if empty or does exist
      [ ${#vdm_database_user} -ge 1 ] || {
        showError "You must enter a database username!"
      }
    done
    # get the database user password needed
    while [ ${#vdm_database_pass} -le 1 ]; do
      # get the value
      vdm_database_pass=$(getPassword "Enter Database User Password" \
        "$(getRandomPass 20)" 'Enter Database User Password') || return $?
      # keep asking if empty or does exist
      [ ${#vdm_database_pass} -ge 1 ] || {
        showError "You must enter a database user password!"
      }
    done
    # get the database root password
    while [ ${#vdm_database_rootpass} -le 1 ]; do
      # get the value
      vdm_database_rootpass=$(getPassword "Enter Database Root Password" \
        "$(getRandomPass 40)" 'Enter Database Root Password') || return $?
      # keep asking if empty or does exist
      [ ${#vdm_database_rootpass} -ge 1 ] || {
        showError "You must enter a database root password!"
      }
    done
  }
  # set persistence
  VDM_JOOMLA_VOLUMES_MOUNT=$(getYMLine3 "- \"\${VDM_PROJECT_PATH}/${VDM_KEY}/joomla:/var/www/html\"")
  VDM_DB_VOLUMES_MOUNT=$(getYMLine3 "- \"\${VDM_PROJECT_PATH}/${VDM_KEY}/db:/var/lib/mysql\"")
  VDM_EXTRA_CONTAINER_STUFF=''
  VDM_EXTRA_JOOMLA_ENV=''
  VDM_VOLUMES='volumes:'
  reset_volume=true
  # only if in expert mode
  if isExpert && ! setPersistence 'Joomla website files and folders'; then
    VDM_JOOMLA_VOLUMES_MOUNT=$(getYMLine3 "- ${VDM_KEY,,}_web:/var/www/html")
    VDM_VOLUMES+=$(getYMLine1 "${VDM_KEY,,}_web:")
    reset_volume=false
  fi
  # only if in expert mode
  if isExpert && ! setPersistence 'Joomla database'; then
    VDM_DB_VOLUMES_MOUNT=$(getYMLine3 "- ${VDM_KEY,,}_db:/var/lib/mysql")
    VDM_VOLUMES+=$(getYMLine1 "${VDM_KEY,,}_db:")
    reset_volume=false
  fi
  # check if we have to reset the volume value
  $reset_volume && VDM_VOLUMES=''
  # add the projects path
  setContainerEnvVariable "VDM_PROJECT_PATH=\"${VDM_PROJECT_PATH}\"" || return $?
  # only if in expert mode set the container user detail id needed
  if isExpert; then
    # ask if we should add mailcatcher
    if getInputYesNo "Would you also like to enable mailcatcher for these ${VDM_CONTAINER_TYPE^} containers" \
      "Enable Mailcatcher" 8 112 "defaultno"; then
      VDM_EXTRA_CONTAINER_STUFF=$(getYMLine1 "mailcatcher${VDM_KEY}:")
      VDM_EXTRA_CONTAINER_STUFF+=$(getYMLine2 "image: schickling/mailcatcher")
      VDM_EXTRA_CONTAINER_STUFF+=$(getYMLine2 "container_name: mailcatcher${VDM_KEY}")
      VDM_EXTRA_CONTAINER_STUFF+=$(getYMLine2 "restart: unless-stopped")
      VDM_EXTRA_CONTAINER_STUFF+=$(getYMLine2 "networks:")
      VDM_EXTRA_CONTAINER_STUFF+=$(getYMLine3 "- traefik")
      VDM_EXTRA_CONTAINER_STUFF+=$(getYMLine2 "labels:")
      VDM_EXTRA_CONTAINER_STUFF+=$(getYMLine3 "# mailcatcher")
      VDM_EXTRA_CONTAINER_STUFF+=$(getYMLine3 "- \"traefik.enable=true\"")
      VDM_EXTRA_CONTAINER_STUFF+=$(getYMLine3 "- \"traefik.http.routers.mailcatcher${VDM_KEY}.rule=Host(\`${VDM_SUBDOMAIN}mail.${VDM_DOMAIN}\`)\"")
      if $VDM_SECURE; then
        VDM_EXTRA_CONTAINER_STUFF+=$(getYMLine3 "- \"traefik.http.routers.mailcatcher${VDM_KEY}.entrypoints=${VDM_ENTRY_POINT}\"")
        VDM_EXTRA_CONTAINER_STUFF+=$(getYMLine3 "- \"traefik.http.routers.mailcatcher${VDM_KEY}.tls.certresolver=${VDM_CERT_RESOLVER}\"")
      fi
      VDM_EXTRA_CONTAINER_STUFF+=$(getYMLine3 "- \"traefik.http.routers.mailcatcher${VDM_KEY}.service=mailcatcher${VDM_KEY}\"")
      VDM_EXTRA_CONTAINER_STUFF+=$(getYMLine3 "- \"traefik.http.services.mailcatcher${VDM_KEY}.loadbalancer.server.port=1080\"")
      VDM_EXTRA_JOOMLA_ENV+=$(getYMLine3 "- JOOMLA_SMTP_HOST=mailcatcher${VDM_KEY}:1025")
    fi
    # if this is our octoleo images we can also set the user ID and user-group ID
    setContainerUser "$(id -u)" || return $?
    # check that we got the details
    if [ -n "${VDM_PUID}" ] && [ -n "${VDM_PGID}" ]; then
      setContainerEnvVariable "VDM_${VDM_ENV_KEY^^}_PUID=\"#${VDM_PUID}\"" || return $?
      setContainerEnvVariable "VDM_${VDM_ENV_KEY^^}_PGID=\"#${VDM_PGID}\"" || return $?
    fi
  fi
  # add this value if not set variable
  [ ${#vdm_database_name} -ge 1 ] && setContainerEnvVariable "VDM_${VDM_ENV_KEY^^}_DB=\"${vdm_database_name}\""
  # add this value if not set variable
  [ ${#vdm_database_user} -ge 1 ] && setContainerEnvVariable "VDM_${VDM_ENV_KEY^^}_DB_USER=\"${vdm_database_user}\""
  # add this value if not set variable
  [ ${#vdm_database_pass} -ge 1 ] && setContainerEnvVariable "VDM_${VDM_ENV_KEY^^}_DB_PASS=\"${vdm_database_pass}\""
  # add this value if not set variable
  [ ${#vdm_database_rootpass} -ge 1 ] && setContainerEnvVariable "VDM_${VDM_ENV_KEY^^}_DB_ROOT=\"${vdm_database_rootpass}\""
  # we only do autodeploy for Joomla 4.3 and above
  if isVersionAbove "$VDM_JV" "4.3"; then
    # setup the website auto deploy details
    setJoomlaWebsiteDetails || return $?
    if [[ -n "${VDM_J_EMAIL}" ]]; then
      # add extra Joomla envs
      setContainerEnvVariable "VDM_${VDM_ENV_KEY^^}_JOOMLA_DB_TYPE=\"mysqli\"" || return $?
      setContainerEnvVariable "VDM_${VDM_ENV_KEY^^}_JOOMLA_DB_PREFIX=\"${VDM_KEY}_\"" || return $?
      setContainerEnvVariable "VDM_${VDM_ENV_KEY^^}_JOOMLA_SITE_NAME=\"${VDM_J_SITE_NAME}\"" || return $?
      setContainerEnvVariable "VDM_${VDM_ENV_KEY^^}_JOOMLA_ADMIN_USERNAME=\"${VDM_J_USERNAME}\"" || return $?
      setContainerEnvVariable "VDM_${VDM_ENV_KEY^^}_JOOMLA_ADMIN_USER=\"${VDM_J_USER}\"" || return $?
      setContainerEnvVariable "VDM_${VDM_ENV_KEY^^}_JOOMLA_ADMIN_EMAIL=\"${VDM_J_EMAIL}\"" || return $?
      setContainerEnvVariable "VDM_${VDM_ENV_KEY^^}_JOOMLA_ADMIN_PASSWORD=\"${VDM_J_PASSWORD}\"" || return $?
      VDM_EXTRA_JOOMLA_ENV+=$(getYMLine3 "- JOOMLA_DB_TYPE=\${VDM_${VDM_ENV_KEY^^}_JOOMLA_DB_TYPE}")
      VDM_EXTRA_JOOMLA_ENV+=$(getYMLine3 "- JOOMLA_DB_PREFIX=\${VDM_${VDM_ENV_KEY^^}_JOOMLA_DB_PREFIX}")
      VDM_EXTRA_JOOMLA_ENV+=$(getYMLine3 "- JOOMLA_SITE_NAME=\${VDM_${VDM_ENV_KEY^^}_JOOMLA_SITE_NAME}")
      VDM_EXTRA_JOOMLA_ENV+=$(getYMLine3 "- JOOMLA_ADMIN_USERNAME=\${VDM_${VDM_ENV_KEY^^}_JOOMLA_ADMIN_USERNAME}")
      VDM_EXTRA_JOOMLA_ENV+=$(getYMLine3 "- JOOMLA_ADMIN_USER=\${VDM_${VDM_ENV_KEY^^}_JOOMLA_ADMIN_USER}")
      VDM_EXTRA_JOOMLA_ENV+=$(getYMLine3 "- JOOMLA_ADMIN_EMAIL=\${VDM_${VDM_ENV_KEY^^}_JOOMLA_ADMIN_EMAIL}")
      VDM_EXTRA_JOOMLA_ENV+=$(getYMLine3 "- JOOMLA_ADMIN_PASSWORD=\${VDM_${VDM_ENV_KEY^^}_JOOMLA_ADMIN_PASSWORD}")
    fi
    if [[ -n "${VDM_J_EXTENSIONS_URLS}" && "${#VDM_J_EXTENSIONS_URLS}" -gt 2 ]]; then
      # add extra Joomla envs
      setContainerEnvVariable "VDM_${VDM_ENV_KEY^^}_EXTENSIONS_URLS=\"${VDM_J_EXTENSIONS_URLS}\"" || return $?
      VDM_EXTRA_JOOMLA_ENV+=$(getYMLine3 "- JOOMLA_EXTENSIONS_URLS=\${VDM_${VDM_ENV_KEY^^}_EXTENSIONS_URLS}")
    fi
    if [[ -n "${VDM_J_CLI_COMMANDS}" && "${#VDM_J_CLI_COMMANDS}" -gt 2 ]]; then
      # add extra Joomla envs
      setContainerEnvVariable "VDM_${VDM_ENV_KEY^^}_CLI_COMMANDS=\"${VDM_J_CLI_COMMANDS}\"" || return $?
      VDM_EXTRA_JOOMLA_ENV+=$(getYMLine3 "- JOOMLA_CLI_COMMANDS=\${VDM_${VDM_ENV_KEY^^}_CLI_COMMANDS}")
    fi
  fi
  # add PHP settings
  VDM_PHP_PROJECT_PATH="${VDM_KEY}"
  export VDM_PHP_PROJECT_PATH
  local customization_status
  if isExpert; then
    if setPHPSettings; then
      VDM_JOOMLA_VOLUMES_MOUNT+=$(getYMLine3 "- \"\${VDM_PROJECT_PATH}/${VDM_PHP_PROJECT_PATH}/php.ini:/var/www/html/php.ini\"")
    else
      customization_status=$?
      [ "$customization_status" -eq 1 ] || return "$customization_status"
    fi
  fi
  # customize docker-entrypoint.sh
  VDM_ENTRY_PROJECT_PATH="${VDM_KEY}"
  export VDM_ENTRY_PROJECT_PATH
  if isExpert; then
    if setDockerEntrypoint; then
      VDM_JOOMLA_VOLUMES_MOUNT+=$(getYMLine3 "- \"\${VDM_PROJECT_PATH}/${VDM_ENTRY_PROJECT_PATH}/entrypoint.sh:/entrypoint.sh\"")
    else
      customization_status=$?
      [ "$customization_status" -eq 1 ] || return "$customization_status"
    fi
  fi
  ##########################
  ### export all we need
  # global
  export VDM_CONTAINER_TYPE
  export VDM_REPO_PATH
  export VDM_PROJECT_PATH
  # container
  export VDM_REMOVE_SECURE
  export VDM_ENTRY_POINT
  export VDM_CERT_RESOLVER
  export VDM_HTTP_SCHEME
  export VDM_PERSISTENCE
  export VDM_NOT_PERSISTENCE
  export VDM_VOLUMES
  export VDM_JOOMLA_VOLUMES_MOUNT
  export VDM_DB_VOLUMES_MOUNT
  export VDM_EXTRA_CONTAINER_STUFF
  export VDM_JOOMLA_SECURE_LABELS
  export VDM_PHPMYADMIN_SECURE_LABELS
  export VDM_EXTRA_JOOMLA_ENV
  # container lower
  export vdm_database_name
  export vdm_database_user
  export vdm_database_pass
  export vdm_database_rootpass
  # set host file if needed
  updateHostFile
  # also set the database domain
  updateHostFile "${VDM_SUBDOMAIN}db"
  saveContainerCompose joomlaContainer "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/available/${VDM_SUBDOMAIN}.${VDM_DOMAIN}/docker-compose.yml" || return 1
  # saved the file
  showNotice "Saved ${VDM_CONTAINER_TYPE}:docker-compose.yml file.\nSetup of this container is complete!"
  # ask if we should continue to enable
  if getInputYesNo "Would you also like to enable this ${VDM_CONTAINER_TYPE^} container" \
    "Enable Container" 8 112 "defaultno"; then
    # we set the container details
    export VDM_CONTAINER="${VDM_SUBDOMAIN}.${VDM_DOMAIN}"
    # then we enable it
    enableContainer "${VDM_CONTAINER_TYPE}" || return $?
  fi
  # display the configurations
  showJoomlaConfigDetails
  ##########################
  ### unset all no longer needed
  # container
  unset VDM_SUBDOMAIN
  unset VDM_J_REPO
  unset VDM_ENTRY_REPO
  unset VDM_JV
  unset VDM_KEY
  unset VDM_ENV_KEY
  unset VDM_REMOVE_SECURE
  unset VDM_ENTRY_POINT
  unset VDM_CERT_RESOLVER
  unset VDM_HTTP_SCHEME
  unset VDM_PERSISTENCE
  unset VDM_NOT_PERSISTENCE
  unset VDM_VOLUMES
  unset VDM_JOOMLA_VOLUMES_MOUNT
  unset VDM_DB_VOLUMES_MOUNT
  unset VDM_PHP_PROJECT_PATH
  unset VDM_ENTRY_PROJECT_PATH
  unset VDM_EXTRA_CONTAINER_STUFF
  unset VDM_JOOMLA_SECURE_LABELS
  unset VDM_PHPMYADMIN_SECURE_LABELS
  unset VDM_EXTRA_JOOMLA_ENV
  unset VDM_J_SITE_NAME
  unset VDM_J_USERNAME
  unset VDM_J_USER
  unset VDM_J_EMAIL
  unset VDM_J_PASSWORD
  unset VDM_J_EXTENSIONS_URLS
  unset VDM_J_CLI_COMMANDS
  # container lower
  unset vdm_database_name
  unset vdm_database_user
  unset vdm_database_pass
  unset vdm_database_rootpass
  # return a success
  return 0
}

# return the Joomla Container setup yml
function joomlaContainer() {

  vdm_container_user=''
  if [ -n "${VDM_PUID}" ] && [ -n "${VDM_PGID}" ]; then
    vdm_container_user="
      - APACHE_RUN_USER=\${VDM_${VDM_ENV_KEY^^}_PUID}
      - APACHE_RUN_GROUP=\${VDM_${VDM_ENV_KEY^^}_PGID}"
  fi

  cat <<EOF
services:
  mariadb${VDM_KEY}:
    image: mariadb:latest
    container_name: mariadb${VDM_KEY}
    restart: unless-stopped

    environment:
      - MARIADB_DATABASE=\${VDM_${VDM_ENV_KEY^^}_DB}
      - MARIADB_USER=\${VDM_${VDM_ENV_KEY^^}_DB_USER}
      - MARIADB_PASSWORD=\${VDM_${VDM_ENV_KEY^^}_DB_PASS}
      - MARIADB_ROOT_PASSWORD=\${VDM_${VDM_ENV_KEY^^}_DB_ROOT}

    volumes:${VDM_DB_VOLUMES_MOUNT}

    networks:
      - traefik

    healthcheck:
      test: ["CMD-SHELL", "mariadb-admin ping --silent"]
      interval: 20s
      timeout: 5s
      retries: 5

  joomla${VDM_KEY}:
    image: ${VDM_J_REPO}:${VDM_JV}
    container_name: joomla${VDM_KEY}
    restart: unless-stopped

    # Implicit internal Traefik only.
    expose:
      - "80"

    environment:${vdm_container_user}
      - JOOMLA_DB_HOST=mariadb${VDM_KEY}:3306
      - JOOMLA_DB_NAME=\${VDM_${VDM_ENV_KEY^^}_DB}
      - JOOMLA_DB_USER=\${VDM_${VDM_ENV_KEY^^}_DB_USER}
      - JOOMLA_DB_PASSWORD=\${VDM_${VDM_ENV_KEY^^}_DB_PASS}${VDM_EXTRA_JOOMLA_ENV}

    depends_on:
      mariadb${VDM_KEY}:
        condition: service_healthy

    volumes:${VDM_JOOMLA_VOLUMES_MOUNT}

    networks:
      - traefik

     # Easy basic limits
#    deploy:
#      resources:
#        limits:
#          cpus: '1.5'
#          memory: 2G
#        reservations:
#          memory: 512M

    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost/"]
      interval: 30s
      timeout: 5s
      retries: 5

    labels:
      - "traefik.enable=true"
      - "traefik.http.routers.joomla${VDM_KEY}.rule=Host(\`${VDM_SUBDOMAIN}.${VDM_DOMAIN}\`)"${VDM_JOOMLA_SECURE_LABELS}

  phpmyadmin${VDM_KEY}:
    image: phpmyadmin/phpmyadmin
    container_name: phpmyadmin${VDM_KEY}
    restart: unless-stopped

    # Implicit internal Traefik only.
    expose:
      - "80"

    environment:
      PMA_HOST: mariadb${VDM_KEY}
      PMA_PORT: 3306
      UPLOAD_LIMIT: 300M

    depends_on:
      mariadb${VDM_KEY}:
        condition: service_healthy

    networks:
      - traefik

    labels:
      - "traefik.enable=true"
      - "traefik.http.routers.phpmyadmin${VDM_KEY}.rule=Host(\`${VDM_SUBDOMAIN}db.${VDM_DOMAIN}\`)"${VDM_PHPMYADMIN_SECURE_LABELS}${VDM_EXTRA_CONTAINER_STUFF}

networks:
  traefik:
    external: true
    name: ${VDM_TRAEFIK_GATEWAY:-traefik_webgateway}

${VDM_VOLUMES}

EOF
}

#####################################################################################################################VDM
######################################## BULK SETUP JOOMLA
function joomla__TRuST__bulk() {
  # load this container type globals
  # shellcheck disable=SC1090
  if [ -f "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/.env" ]; then
    loadEnvFile "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/.env" || return 1
  fi
  # we need to pull these values from the env if set
  local vdm_key
  local vdm_subdomain
  local vdm_database_name
  local vdm_bulk_database_name
  local vdm_database_user
  local vdm_bulk_database_user
  local vdm_database_pass
  local vdm_bulk_database_user
  local vdm_database_rootpass
  local vdm_middlewares
  # get the Joomla image source
  setImageSource || return $?
  # set the domain
  setDomain || return $?
  # get the sub domain if not set TODO get dynamic joomla domain name
  setSubDomain "subdomain" "joomla" || return $?
  vdm_subdomain="${VDM_SUBDOMAIN}"
  # check if we have secure switch set
  setSecureState
  # setup letsencrypt stuff
  VDM_REMOVE_SECURE=''
  VDM_ENTRY_POINT="websecure"
  VDM_HTTP_SCHEME="https://"
  VDM_CERT_RESOLVER="vdmresolver"
  if $VDM_SECURE; then
    setSecureCloudflareState "joomla"
    vdm_middlewares="joomla-security"
    if $VDM_SECURE_CLOUDFLARE; then
      VDM_CERT_RESOLVER="cfresolver"
      vdm_middlewares="cloudflare,joomla-security"
    fi
  else
    VDM_REMOVE_SECURE="#"
    VDM_ENTRY_POINT="web"
    VDM_HTTP_SCHEME="http://"
  fi
  # get the database name needed
  while [ ${#vdm_bulk_database_name} -le 1 ]; do
    # get the value
    vdm_bulk_database_name=$(getInput "Enter Database Name\n[Text with no spaces that is only underscore and alphabetical]" \
      "vdm_io" 'Enter Database Name') || return $?
    # keep asking if empty or does exist
    [ ${#vdm_bulk_database_name} -ge 1 ] || {
      showError "You must enter a database name!"
    }
  done
  # get the database user name needed
  while [ ${#vdm_bulk_database_user} -le 1 ]; do
    # get the value
    vdm_bulk_database_user=$(getInput "Enter Database Username\n[Text with no spaces that is only underscore and alphabetical]" \
      "vdm_user" 'Enter Database Username') || return $?
    # keep asking if empty or does exist
    [ ${#vdm_bulk_database_user} -ge 1 ] || {
      showError "You must enter a database username!"
    }
  done
  # get the database user password needed
  while [ ${#vdm_bulk_database_pass} -le 1 ]; do
    # get the value
    vdm_bulk_database_pass=$(getPassword "Enter Database User Password" \
      "$(getRandomPass 20)" 'Enter Database User Password') || return $?
    # keep asking if empty or does exist
    [ ${#vdm_bulk_database_pass} -ge 1 ] || {
      showError "You must enter a database user password!"
    }
  done
  # only if in expert mode set the container user detail id needed
  if isExpert; then
    # if this is our octoleo images we can also set the user ID and user-group ID
    setContainerUser "$(id -u)" || return $?
  fi
  # add PHP settings
  set_php_settings=false
  VDM_PHP_PROJECT_PATH="bulk"
  export VDM_PHP_PROJECT_PATH
  local customization_status
  if isExpert; then
    if setPHPSettings; then
      set_php_settings=true
    else
      customization_status=$?
      [ "$customization_status" -eq 1 ] || return "$customization_status"
    fi
  fi
  # customize docker-entrypoint.sh
  set_docker_entry_point=false
  VDM_ENTRY_PROJECT_PATH="bulk"
  export VDM_ENTRY_PROJECT_PATH
  if isExpert; then
    if setDockerEntrypoint; then
      set_docker_entry_point=true
    else
      customization_status=$?
      [ "$customization_status" -eq 1 ] || return "$customization_status"
    fi
  fi
  # set persistence
  persistence_volume=false
  persistence_db=false
  # only if in expert mode
  if isExpert && setPersistence 'Joomla website files and folders'; then
    persistence_volume=true
  fi
  # only if in expert mode
  if isExpert && setPersistence 'Joomla database'; then
    persistence_db=true
  fi
  # ask if we should add mailcatcher
  enable_mailcatcher=false
  if getInputYesNo "Would you also like to enable mailcatcher for these ${VDM_CONTAINER_TYPE^} containers" \
    "Enable Mailcatcher" 8 112 "defaultno"; then
      enable_mailcatcher=true
  fi
  # we only do autodeploy for Joomla 4.3 and above
  enable_autodeploy=false
  enable_extension_autodeploy=false
  enable_command_autodeploy=false
  if isVersionAbove "$VDM_JV" "4.3"; then
    # get website setup details
    setJoomlaWebsiteDetails || return $?
    if [[ -n "${VDM_J_EMAIL}" ]]; then
      enable_autodeploy=true
      if [[ -n "${VDM_J_EXTENSIONS_URLS}" && "${#VDM_J_EXTENSIONS_URLS}" -gt 2 ]]; then
        enable_extension_autodeploy=true
      fi
      if [[ -n "${VDM_J_CLI_COMMANDS}" && "${#VDM_J_CLI_COMMANDS}" -gt 2 ]]; then
        enable_command_autodeploy=true
      fi
    fi
  fi
  # add the projects path
  setContainerEnvVariable "VDM_PROJECT_PATH=\"${VDM_PROJECT_PATH}\"" || return $?
  ##########################
  ### export all we need
  # global
  export VDM_CONTAINER_TYPE
  export VDM_REPO_PATH
  export VDM_PROJECT_PATH
  # container
  export VDM_REMOVE_SECURE
  export VDM_ENTRY_POINT
  export VDM_CERT_RESOLVER
  export VDM_HTTP_SCHEME
  export VDM_PERSISTENCE
  export VDM_NOT_PERSISTENCE
  # get the number of containers
  setNumberContainers || return $?
  # ask if we should continue to enable
  enable_containers=false
  if getInputYesNo "Would you also like to enable all these ${VDM_CONTAINER_TYPE^} containers" \
    "Enable Containers" 8 112 "defaultno"; then
      enable_containers=true
  fi
  # loop the number of containers
  for (( i=1; i<=VDM_NUMBER_CONTAINERS; i++ ))
  do
    vdm_key=$(getRandomName 5)
    VDM_KEY="${vdm_key,,}"
    VDM_ENV_KEY="${vdm_key^^}"
    VDM_SUBDOMAIN="${vdm_subdomain}${i}"
    vdm_database_name="${vdm_bulk_database_name}${i}"
    vdm_database_user="${vdm_bulk_database_user}${i}"
    vdm_database_pass="${vdm_bulk_database_pass}${i}"
    vdm_database_rootpass=$(getRandomPass 30)
    # reset some globals
    VDM_EXTRA_CONTAINER_STUFF=''
    VDM_EXTRA_JOOMLA_ENV=''
    # check that we got the details
    if [ -n "${VDM_PUID}" ] && [ -n "${VDM_PGID}" ]; then
      setContainerEnvVariable "VDM_${VDM_ENV_KEY^^}_PUID=\"#${VDM_PUID}\"" || return $?
      setContainerEnvVariable "VDM_${VDM_ENV_KEY^^}_PGID=\"#${VDM_PGID}\"" || return $?
    fi
    # add this value if not set variable
    setContainerEnvVariable "VDM_${VDM_ENV_KEY^^}_DB=\"${vdm_database_name}\"" || return $?
    # add this value if not set variable
    setContainerEnvVariable "VDM_${VDM_ENV_KEY^^}_DB_USER=\"${vdm_database_user}\"" || return $?
    # add this value if not set variable
    setContainerEnvVariable "VDM_${VDM_ENV_KEY^^}_DB_PASS=\"${vdm_database_pass}\"" || return $?
    # add this value if not set variable
    setContainerEnvVariable "VDM_${VDM_ENV_KEY^^}_DB_ROOT=\"${vdm_database_rootpass}\"" || return $?
    # we only do autodeploy for Joomla 4.3 and above
    if $enable_autodeploy; then
      # add extra Joomla envs
      setContainerEnvVariable "VDM_${VDM_ENV_KEY^^}_JOOMLA_DB_TYPE=\"mysqli\"" || return $?
      setContainerEnvVariable "VDM_${VDM_ENV_KEY^^}_JOOMLA_DB_PREFIX=\"${VDM_KEY}_\"" || return $?
      setContainerEnvVariable "VDM_${VDM_ENV_KEY^^}_JOOMLA_SITE_NAME=\"${VDM_J_SITE_NAME} ${i}\"" || return $?
      setContainerEnvVariable "VDM_${VDM_ENV_KEY^^}_JOOMLA_ADMIN_USERNAME=\"${VDM_J_USERNAME}\"" || return $?
      setContainerEnvVariable "VDM_${VDM_ENV_KEY^^}_JOOMLA_ADMIN_USER=\"${VDM_J_USER}\"" || return $?
      setContainerEnvVariable "VDM_${VDM_ENV_KEY^^}_JOOMLA_ADMIN_EMAIL=\"${VDM_J_EMAIL}\"" || return $?
      setContainerEnvVariable "VDM_${VDM_ENV_KEY^^}_JOOMLA_ADMIN_PASSWORD=\"${VDM_J_PASSWORD}\"" || return $?
      VDM_EXTRA_JOOMLA_ENV+=$(getYMLine3 "- JOOMLA_DB_TYPE=\${VDM_${VDM_ENV_KEY^^}_JOOMLA_DB_TYPE}")
      VDM_EXTRA_JOOMLA_ENV+=$(getYMLine3 "- JOOMLA_DB_PREFIX=\${VDM_${VDM_ENV_KEY^^}_JOOMLA_DB_PREFIX}")
      VDM_EXTRA_JOOMLA_ENV+=$(getYMLine3 "- JOOMLA_SITE_NAME=\${VDM_${VDM_ENV_KEY^^}_JOOMLA_SITE_NAME}")
      VDM_EXTRA_JOOMLA_ENV+=$(getYMLine3 "- JOOMLA_ADMIN_USERNAME=\${VDM_${VDM_ENV_KEY^^}_JOOMLA_ADMIN_USERNAME}")
      VDM_EXTRA_JOOMLA_ENV+=$(getYMLine3 "- JOOMLA_ADMIN_USER=\${VDM_${VDM_ENV_KEY^^}_JOOMLA_ADMIN_USER}")
      VDM_EXTRA_JOOMLA_ENV+=$(getYMLine3 "- JOOMLA_ADMIN_EMAIL=\${VDM_${VDM_ENV_KEY^^}_JOOMLA_ADMIN_EMAIL}")
      VDM_EXTRA_JOOMLA_ENV+=$(getYMLine3 "- JOOMLA_ADMIN_PASSWORD=\${VDM_${VDM_ENV_KEY^^}_JOOMLA_ADMIN_PASSWORD}")
      if $enable_extension_autodeploy; then
        # add extra Joomla envs
        setContainerEnvVariable "VDM_${VDM_ENV_KEY^^}_EXTENSIONS_URLS=\"${VDM_J_EXTENSIONS_URLS}\"" || return $?
        VDM_EXTRA_JOOMLA_ENV+=$(getYMLine3 "- JOOMLA_EXTENSIONS_URLS=\${VDM_${VDM_ENV_KEY^^}_EXTENSIONS_URLS}")
      fi
      if $enable_command_autodeploy; then
        # add extra Joomla envs
        setContainerEnvVariable "VDM_${VDM_ENV_KEY^^}_CLI_COMMANDS=\"${VDM_J_CLI_COMMANDS}\"" || return $?
        VDM_EXTRA_JOOMLA_ENV+=$(getYMLine3 "- JOOMLA_CLI_COMMANDS=\${VDM_${VDM_ENV_KEY^^}_CLI_COMMANDS}")
      fi
    fi
    # set persistence
    reset_volume=true
    VDM_JOOMLA_VOLUMES_MOUNT=$(getYMLine3 "- \"\${VDM_PROJECT_PATH}/${VDM_KEY}/joomla:/var/www/html\"")
    VDM_DB_VOLUMES_MOUNT=$(getYMLine3 "- \"\${VDM_PROJECT_PATH}/${VDM_KEY}/db:/var/lib/mysql\"")
    VDM_VOLUMES='volumes:'
    if ! $persistence_volume; then
      VDM_JOOMLA_VOLUMES_MOUNT=$(getYMLine3 "- ${VDM_KEY,,}_web:/var/www/html")
      VDM_VOLUMES+=$(getYMLine1 "${VDM_KEY,,}_web:")
      reset_volume=false
    fi
    if ! $persistence_db; then
      VDM_DB_VOLUMES_MOUNT=$(getYMLine3 "- ${VDM_KEY,,}_db:/var/lib/mysql")
      VDM_VOLUMES+=$(getYMLine1 "${VDM_KEY,,}_db:")
      reset_volume=false
    fi
    # add PHP settings
    if $set_php_settings; then
      VDM_JOOMLA_VOLUMES_MOUNT+=$(getYMLine3 "- \"\${VDM_PROJECT_PATH}/${VDM_PHP_PROJECT_PATH}/php.ini:/var/www/html/php.ini\"")
    fi
    # customize docker-entrypoint.sh
    if $set_docker_entry_point; then
      VDM_JOOMLA_VOLUMES_MOUNT+=$(getYMLine3 "- \"\${VDM_PROJECT_PATH}/${VDM_ENTRY_PROJECT_PATH}/entrypoint.sh:/entrypoint.sh\"")
    fi
    # check if we have to reset the volume value
    $reset_volume && VDM_VOLUMES=''
    # add the mailcatcher if needed
    if $enable_mailcatcher; then
      VDM_EXTRA_CONTAINER_STUFF=$(getYMLine1 "mailcatcher${VDM_KEY}:")
      VDM_EXTRA_CONTAINER_STUFF+=$(getYMLine2 "image: schickling/mailcatcher")
      VDM_EXTRA_CONTAINER_STUFF+=$(getYMLine2 "container_name: mailcatcher${VDM_KEY}")
      VDM_EXTRA_CONTAINER_STUFF+=$(getYMLine2 "restart: unless-stopped")
      VDM_EXTRA_CONTAINER_STUFF+=$(getYMLine2 "networks:")
      VDM_EXTRA_CONTAINER_STUFF+=$(getYMLine3 "- traefik")
      VDM_EXTRA_CONTAINER_STUFF+=$(getYMLine2 "labels:")
      VDM_EXTRA_CONTAINER_STUFF+=$(getYMLine3 "# mailcatcher")
      VDM_EXTRA_CONTAINER_STUFF+=$(getYMLine3 "- \"traefik.enable=true\"")
      VDM_EXTRA_CONTAINER_STUFF+=$(getYMLine3 "- \"traefik.http.routers.mailcatcher${VDM_KEY}.rule=Host(\`${VDM_SUBDOMAIN}mail.${VDM_DOMAIN}\`)\"")
      if $VDM_SECURE; then
        VDM_EXTRA_CONTAINER_STUFF+=$(getYMLine3 "- \"traefik.http.routers.mailcatcher${VDM_KEY}.entrypoints=${VDM_ENTRY_POINT}\"")
        VDM_EXTRA_CONTAINER_STUFF+=$(getYMLine3 "- \"traefik.http.routers.mailcatcher${VDM_KEY}.tls.certresolver=${VDM_CERT_RESOLVER}\"")
      fi
      VDM_EXTRA_CONTAINER_STUFF+=$(getYMLine3 "- \"traefik.http.routers.mailcatcher${VDM_KEY}.service=mailcatcher${VDM_KEY}\"")
      VDM_EXTRA_CONTAINER_STUFF+=$(getYMLine3 "- \"traefik.http.services.mailcatcher${VDM_KEY}.loadbalancer.server.port=1080\"")
      VDM_EXTRA_JOOMLA_ENV+=$(getYMLine3 "- JOOMLA_SMTP_HOST=mailcatcher${VDM_KEY}:1025")
    fi
    # setup letsencrypt stuff
    VDM_JOOMLA_SECURE_LABELS=''
    VDM_PHPMYADMIN_SECURE_LABELS=''
    if $VDM_SECURE; then
      # add joomla labels
      VDM_JOOMLA_SECURE_LABELS+=$(getYMLine3 "- \"traefik.http.routers.joomla${VDM_KEY}.entrypoints=${VDM_ENTRY_POINT}\"")
      VDM_JOOMLA_SECURE_LABELS+=$(getYMLine3 "- \"traefik.http.routers.joomla${VDM_KEY}.tls.certresolver=${VDM_CERT_RESOLVER}\"")
      VDM_JOOMLA_SECURE_LABELS+=$(getYMLine3 "- \"traefik.http.routers.joomla${VDM_KEY}.service=joomla${VDM_KEY}\"")
      VDM_JOOMLA_SECURE_LABELS+=$(getYMLine3 "- \"traefik.http.routers.joomla${VDM_KEY}.middlewares=${vdm_middlewares}\"")
      VDM_JOOMLA_SECURE_LABELS+=$(getYMLine3 "- \"traefik.http.services.joomla${VDM_KEY}.loadbalancer.server.port=80\"")
      # add phpmyadmin labels
      VDM_PHPMYADMIN_SECURE_LABELS+=$(getYMLine3 "- \"traefik.http.routers.phpmyadmin${VDM_KEY}.entrypoints=${VDM_ENTRY_POINT}\"")
      VDM_PHPMYADMIN_SECURE_LABELS+=$(getYMLine3 "- \"traefik.http.routers.phpmyadmin${VDM_KEY}.tls.certresolver=${VDM_CERT_RESOLVER}\"")
      VDM_PHPMYADMIN_SECURE_LABELS+=$(getYMLine3 "- \"traefik.http.routers.phpmyadmin${VDM_KEY}.service=phpmyadmin${VDM_KEY}\"")
      VDM_PHPMYADMIN_SECURE_LABELS+=$(getYMLine3 "- \"traefik.http.routers.phpmyadmin${VDM_KEY}.middlewares=${vdm_middlewares}\"")
      VDM_PHPMYADMIN_SECURE_LABELS+=$(getYMLine3 "- \"traefik.http.services.phpmyadmin${VDM_KEY}.loadbalancer.server.port=80\"")
    fi
    # global
    export VDM_KEY
    export VDM_ENV_KEY
    export VDM_SUBDOMAIN
    # container
    export VDM_VOLUMES
    export VDM_JOOMLA_VOLUMES_MOUNT
    export VDM_DB_VOLUMES_MOUNT
    export VDM_EXTRA_CONTAINER_STUFF
    export VDM_JOOMLA_SECURE_LABELS
    export VDM_PHPMYADMIN_SECURE_LABELS
    export VDM_EXTRA_JOOMLA_ENV
    # container lower
    export vdm_database_name
    export vdm_database_user
    export vdm_database_pass
    export vdm_database_rootpass
    saveContainerCompose joomlaContainer "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/available/${VDM_SUBDOMAIN}.${VDM_DOMAIN}/docker-compose.yml" || return 1
    # enable the container
    if $enable_containers; then
      # we set the container details
      export VDM_CONTAINER="${VDM_SUBDOMAIN}.${VDM_DOMAIN}"
      # then we enable it
      enableContainer "${VDM_CONTAINER_TYPE}" || return $?
    fi
  done
  ##########################
  ### unset all no longer needed
  # container
  unset VDM_SUBDOMAIN
  unset VDM_J_REPO
  unset VDM_ENTRY_REPO
  unset VDM_JV
  unset VDM_KEY
  unset VDM_ENV_KEY
  unset VDM_REMOVE_SECURE
  unset VDM_ENTRY_POINT
  unset VDM_CERT_RESOLVER
  unset VDM_HTTP_SCHEME
  unset VDM_PERSISTENCE
  unset VDM_NOT_PERSISTENCE
  unset VDM_VOLUMES
  unset VDM_JOOMLA_VOLUMES_MOUNT
  unset VDM_DB_VOLUMES_MOUNT
  unset VDM_NUMBER_CONTAINERS
  unset VDM_PHP_PROJECT_PATH
  unset VDM_ENTRY_PROJECT_PATH
  unset VDM_EXTRA_CONTAINER_STUFF
  unset VDM_JOOMLA_SECURE_LABELS
  unset VDM_PHPMYADMIN_SECURE_LABELS
  unset VDM_J_SITE_NAME
  unset VDM_J_USERNAME
  unset VDM_J_USER
  unset VDM_J_EMAIL
  unset VDM_J_PASSWORD
  unset VDM_J_EXTENSIONS_URLS
  unset VDM_J_CLI_COMMANDS
  # container lower
  unset vdm_database_name
  unset vdm_database_user
  unset vdm_database_pass
  unset vdm_database_rootpass
  # return a success
  return 0
}

#####################################################################################################################VDM
######################################## SETUP OPENSSH
function openssh__TRuST__setup() {
  # load this container type globals
  # shellcheck disable=SC1090
  if [ -f "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/.env" ]; then
    loadEnvFile "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/.env" || return 1
  fi
  # get the ssh port if not set
  while ! [[ "${VDM_PORT:-}" =~ ^[0-9]{1,5}$ ]] ||
    [ "$((10#${VDM_PORT:-0}))" -lt 1 ] || [ "$((10#${VDM_PORT:-0}))" -gt 65535 ] ||
    [ "$((10#${VDM_PORT:-0}))" -eq 22 ]; do
    # get the value
    VDM_PORT=$(getInput 'Enter ssh port to use\n[do not use 22]' '' 'Enter Port') || return $?
    # keep asking
    if ! [[ "${VDM_PORT}" =~ ^[0-9]{1,5}$ ]] ||
      [ "$((10#${VDM_PORT:-0}))" -lt 1 ] || [ "$((10#${VDM_PORT:-0}))" -gt 65535 ] ||
      [ "$((10#${VDM_PORT:-0}))" -eq 22 ]; then
      showError "Enter an SSH port from 1 to 65535, excluding port 22."
    fi
  done
  VDM_PORT=$((10#${VDM_PORT}))
  # set the main domain if not set
  setMainDomain || return $?
  # get the username if not set
  while ! [[ "${VDM_USER_NAME:-}" =~ ^[a-z][a-z0-9-]{0,31}$ ]] ||
    [ -d "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/available/${VDM_USER_NAME}.${VDM_DOMAIN}" ]; do
    # get the value
    VDM_USER_NAME=$(getInput 'Enter username of the container\n[Start with a lowercase letter; use lowercase letters, digits and hyphens, up to 32 characters]' 'ubuntu' 'Enter Username') || return $?
    # keep asking if empty or does exist
    if ! [[ "${VDM_USER_NAME}" =~ ^[a-z][a-z0-9-]{0,31}$ ]]; then
      showError "Enter a username of up to 32 characters, starting with a lowercase letter and using lowercase letters, digits and hyphens."
    elif [ -d "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/available/${VDM_USER_NAME}.${VDM_DOMAIN}" ]; then
      showError "The username:${VDM_USER_NAME} is already used. Select another"
    elif [ ${#VDM_USER_NAME} -le 1 ]; then
      showError "You must enter a username for the container"
    fi
  done
  # be sure to set the container USER ID
  setContainerUser 33 || return $?
  # get the key if not set
  setUniqueKey "Enter key used for container naming." || return $?
  # get the env key if not set
  setEnvironmentKey || return $?
  # we check if it was set
  [ ${#VDM_PUBLIC_KEY_GLOBAL_DIR} -le 1 ] && VDM_PUBLIC_KEY_GLOBAL_DIR="${VDM_PUBLIC_KEY_DIR:-}"
  # get the global directory of the ssh public keys if not set
  while [ ${#VDM_PUBLIC_KEY_GLOBAL_DIR} -le 1 ] || [ ! -d "${VDM_PUBLIC_KEY_GLOBAL_DIR}" ]; do
    # creat the path if it exist
    if [ ${#VDM_PUBLIC_KEY_GLOBAL_DIR} -ge 1 ] && \
      getInputYesNo "Can we create the ${VDM_PUBLIC_KEY_GLOBAL_DIR} ssh folder" \
      "Create the Path" 8 112; then
      createPrivateDirectory -p "${VDM_PUBLIC_KEY_GLOBAL_DIR}" || return $?
    else
      # get the value
      VDM_PUBLIC_KEY_GLOBAL_DIR=$(getInput "Enter the ssh path where we can select the ssh key folders from." \
        "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/.ssh" 'Enter SSH Path') || return $?
      # keep asking if empty or does exist
      if [ ${#VDM_PUBLIC_KEY_GLOBAL_DIR} -ge 1 ] && [ ! -d "${VDM_PUBLIC_KEY_GLOBAL_DIR}" ] && \
        getInputYesNo "Can we create the ${VDM_PUBLIC_KEY_GLOBAL_DIR} ssh folder" \
        "Create the Path" 8 112; then
        createPrivateDirectory -p "${VDM_PUBLIC_KEY_GLOBAL_DIR}" || return $?
      elif [ ${#VDM_PUBLIC_KEY_GLOBAL_DIR} -le 1 ]; then
        showError "You must set a ssh path where we can select the ssh key folders from."
      fi
    fi
  done
  # set the global key env string for the ssh keys
  VDM_ENV_PUBLIC_KEY_U_DIR="VDM_${VDM_ENV_KEY^^}_PUBLIC_KEY_DIR"
  VDM_PUBLIC_KEY_U_DIR=${!VDM_ENV_PUBLIC_KEY_U_DIR}
  # get the directory of this containers public keys if not set
  while [ ${#VDM_PUBLIC_KEY_U_DIR} -le 1 ] || [ ! -d "${VDM_PUBLIC_KEY_U_DIR}" ]; do
    # creat the path if it exist
    if [ ${#VDM_PUBLIC_KEY_U_DIR} -ge 1 ] && \
      getInputYesNo "Can we create this (${VDM_PUBLIC_KEY_U_DIR}) containers' ssh public keys folder" \
      "Create the Path" 8 112; then
      createPrivateDirectory -p "${VDM_PUBLIC_KEY_U_DIR}" || return $?
    else
      # get the value
      VDM_PUBLIC_KEY_U_DIR=$(getSelectedDirectory "Select the containers' ssh public keys folder." \
        "${VDM_PUBLIC_KEY_GLOBAL_DIR}" "${VDM_KEY,,}" 'Select Folder') || return $?
      # keep asking if empty or does exist
      if [ ${#VDM_PUBLIC_KEY_U_DIR} -ge 1 ]; then
        # add the parent dir back
        VDM_PUBLIC_KEY_U_DIR="${VDM_PUBLIC_KEY_GLOBAL_DIR}/${VDM_PUBLIC_KEY_U_DIR}"
        # check if this directory exist
        if [ ! -d "${VDM_PUBLIC_KEY_U_DIR}" ] && \
          getInputYesNo "Can we create this (${VDM_PUBLIC_KEY_U_DIR}) containers' ssh public keys folder" \
          "Create the Path" 8 112; then
          createPrivateDirectory -p "${VDM_PUBLIC_KEY_U_DIR}" || return $?
          # TODO add option to add keys?
        fi
      else
        showError "You must set a containers' ssh public keys folder."
      fi
    fi
  done
  # we must get the project path
  VDM_ENV_PROJECT_DIR="VDM_${VDM_ENV_KEY^^}_PROJECT_DIR"
  VDM_PROJECT_U_DIR=${!VDM_ENV_PROJECT_DIR}
  # get the directory of the ssh public keys if not set
  while [ ${#VDM_PROJECT_U_DIR} -le 1 ] || [ ! -d "${VDM_PROJECT_U_DIR}" ]; do
    # creat the path if it exist
    if [ ${#VDM_PROJECT_U_DIR} -ge 1 ] && \
      getInputYesNo "Can we create the ${VDM_PROJECT_U_DIR} parent mounting directory" \
      "Create the Path" 8 112; then
      createPrivateDirectory -p "${VDM_PROJECT_U_DIR}" || return $?
    else
      # get the value
      VDM_PROJECT_U_DIR=$(getInput "Enter the parent path where we can select the folders to mount to this container." \
        "${VDM_PROJECT_PATH}" 'Enter Path') || return $?
      # keep asking if empty or does exist
      if [ ${#VDM_PROJECT_U_DIR} -ge 1 ] && [ ! -d "${VDM_PROJECT_U_DIR}" ] && \
        getInputYesNo "Can we create the ${VDM_PROJECT_U_DIR} parent mounting directory" \
        "Create the Path" 8 112; then
        createPrivateDirectory -p "${VDM_PROJECT_U_DIR}" || return $?
      elif [ ${#VDM_PROJECT_U_DIR} -le 1 ]; then
        showError "You must set a parent mounting directory path where we can select the folders to mount to this container."
      fi
    fi
  done
  # now load the mounting volumes
  while [ ${#VDM_MOUNT_DIRS} -le 1 ]; do
    # get the value
    VDM_MOUNT_DIRS=$(getSelectedDirectories "Select the directories to mount to this container." \
      "${VDM_PROJECT_U_DIR}" 'Select Folders') || return $?
    # keep asking if empty or does exist
    if [ ${#VDM_MOUNT_DIRS} -le 1 ]; then
      showError "You must set the directories to mount to this container."
    fi
  done
  # convert the string to an array
  IFS=' ' read -r -a vdm_mount_dirs_array <<<"${VDM_MOUNT_DIRS[@]}"
  # build the mount projects
  VDM_VOLUMES_MOUNT=$(getYMLine3 "- \${${VDM_ENV_PUBLIC_KEY_U_DIR}}:/config/ssh_public_keys")
  # loop over the directories to build the
  for mDir in "${vdm_mount_dirs_array[@]}"; do
    # set the full path
    mDir="${mDir//\"/}"
    # when we mount a joomla volume we may not want to mount the database
    mFull="${VDM_PROJECT_U_DIR}/${mDir}/joomla"
    # add to mount projects
    if [ -d "${mFull}" ] && \
      getInputYesNo "Should we ONLY mount the (joomla website files) ${mDir}/joomla directory" \
      "Mount Joomla" 8 112; then
      VDM_VOLUMES_MOUNT+=$(getYMLine3 "- \${VDM_${VDM_ENV_KEY^^}_PROJECT_DIR}/${mDir}/joomla:/app/${mDir}")
    else
      VDM_VOLUMES_MOUNT+=$(getYMLine3 "- \${VDM_${VDM_ENV_KEY^^}_PROJECT_DIR}/${mDir}:/app/${mDir}")
    fi
  done
  # add this value if not set variable
  setContainerEnvVariable "${VDM_ENV_PROJECT_DIR}=\"${VDM_PROJECT_U_DIR}\"" || return $?
  # add this value if not set variable
  setContainerEnvVariable "VDM_PUBLIC_KEY_GLOBAL_DIR=\"${VDM_PUBLIC_KEY_GLOBAL_DIR}\"" || return $?
  # add this value if not set variable
  setContainerEnvVariable "${VDM_ENV_PUBLIC_KEY_U_DIR}=\"${VDM_PUBLIC_KEY_U_DIR}\"" || return $?
  ##########################
  ### export all we need
  # global
  export VDM_CONTAINER_TYPE
  export VDM_REPO_PATH
  export VDM_PROJECT_PATH
  # container
  export VDM_PORT
  export VDM_USER_NAME
  export VDM_PUBLIC_KEY_GLOBAL_DIR
  export VDM_PUBLIC_KEY_U_DIR
  export VDM_VOLUMES_MOUNT
  export VDM_PROJECT_U_DIR
  saveContainerCompose opensshContainer "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/available/${VDM_USER_NAME}.${VDM_DOMAIN}/docker-compose.yml" || return 1
  # saved the file
  showNotice "Saved ${VDM_CONTAINER_TYPE}:docker-compose.yml file.\nSetup of this container is complete!"
  # ask if we should continue to enable
  if getInputYesNo "Would you also like to enable this ${VDM_CONTAINER_TYPE^} container" \
    "Enable Container" 8 112 "defaultno"; then
    # we set the container details
    export VDM_CONTAINER="${VDM_USER_NAME}.${VDM_DOMAIN}"
    # then we enable it
    enableContainer "${VDM_CONTAINER_TYPE}" || return $?
  fi
  ##########################
  ### unset all no longer needed
  # container
  unset VDM_PORT
  unset VDM_USER_NAME
  unset VDM_KEY
  unset VDM_ENV_KEY
  unset VDM_PUBLIC_KEY_GLOBAL_DIR
  unset VDM_PUBLIC_KEY_U_DIR
  unset VDM_VOLUMES_MOUNT
  unset VDM_PROJECT_U_DIR
  # return a success
  return 0
}

# return the Openssh Container setup yml
function opensshContainer() {
  # we build the yml file
  cat <<EOF
services:
  openssh-server-${VDM_KEY}:
    image: lscr.io/linuxserver/openssh-server
    container_name: openssh-server-${VDM_KEY}
    restart: unless-stopped
    hostname: ${VDM_DOMAIN:-vdm.dev}
    environment:
      - PUID=${VDM_PUID}
      - PGID=${VDM_PGID}
      - TZ=${VDM_TZ:-Africa/Windhoek}
      - PUBLIC_KEY_DIR=/config/ssh_public_keys
      - SUDO_ACCESS=${VDM_SUDO_ACCESS:-false}
      - USER_NAME=${VDM_USER_NAME:-ubuntu}
    volumes:${VDM_VOLUMES_MOUNT}
    ports:
      - ${VDM_PORT}:2222
    networks:
      - openssh

networks:
  openssh:
    external: true
    name: ${VDM_OPENSSH_GATEWAY:-openssh_gateway}
EOF
}

#####################################################################################################################VDM
######################################## EDIT JOOMLA
function joomla__TRuST__edit() {
  # check if this type have available containers
  if ! hasDirectories "${VDM_CONTAINER_TYPE}/available/"; then
    showError "The path ${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/available/ does not exist or is empty, first run a ${VDM_CONTAINER_TYPE^} setup."
  else
    # set some local variables
    local vdm_edit_me
    local container
    # list containers... and allow selection to edit
    container=$(getSelectedDirectory "Select a container to manually edit the docker-composer.yml file.\n[Only continue if you know what your doing!]" \
      "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/available/" '' "Edit ${VDM_CONTAINER_TYPE^} Container") || return 0
    # check that we have something, else return to main menu
    if [ ${#container} -ge 1 ]; then
      # add the parent dir back
      vdm_edit_me="${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/available/${container}/docker-compose.yml"
      # check if this docker-composer.yml exist
      if [ -f "${vdm_edit_me}" ]; then
        # give little heads-up
        showNotice "${USER^}, to save the changes you've made or to just close the file again press:\n\n[ctrl+x] with nano on ubuntu." 13
        # lets open the file with nano for now
        "${EDITOR:-nano}" "${vdm_edit_me}" || return $?
        # if this container is enabled ask if it should be redeployed
        if [ -d "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/enabled/${container}" ] &&
          (whiptail --yesno "Would you like to re-deploy the (${container}) container that you opened to edit?" \
            --title "Re-Deploy Container" --backtitle "${BACK_TITLE}" 8 112); then
          # we set the container details
          export VDM_CONTAINER="${container}"
          # then we enable it
          enableContainer "${VDM_CONTAINER_TYPE}"
        fi
      fi
    fi
  fi
}

#####################################################################################################################VDM
######################################## EDIT OPENSSH
function openssh__TRuST__edit() {
  # check if this type have available containers
  if ! hasDirectories "${VDM_CONTAINER_TYPE}/available/"; then
    showError "The path ${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/available/ does not exist or is empty, first run a ${VDM_CONTAINER_TYPE^} setup."
  else
    # set some local variables
    local vdm_edit_me
    local container
    # list containers... and allow selection to edit
    container=$(getSelectedDirectory "Select a container to manually edit the docker-composer.yml file.\n[Only continue if you know what your doing!]" \
      "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/available/" '' "Edit ${VDM_CONTAINER_TYPE^} Container")
    # check that we have something, else return to main menu
    if [ ${#container} -ge 1 ]; then
      # add the parent dir back
      vdm_edit_me="${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/available/${container}/docker-compose.yml"
      # check if this docker-composer.yml exist
      if [ -f "${vdm_edit_me}" ]; then
        # give little heads-up
        showNotice "${USER^}, to save the changes you've made or to just close the file again press:\n\n[ctrl+x] with nano on ubuntu." 13
        # lets open the file with nano for now
        "${EDITOR:-nano}" "${vdm_edit_me}" || return $?
        # if this container is enabled ask if it should be redeployed
        if [ -d "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/enabled/${container}" ] &&
          (whiptail --yesno "Would you like to re-deploy the (${container}) container that you opened to edit?" \
            --title "Re-Deploy Container" --backtitle "${BACK_TITLE}" 8 112); then
          # we set the container details
          export VDM_CONTAINER="${container}"
          # then we enable it
          enableContainer "${VDM_CONTAINER_TYPE}"
        fi
      fi
    fi
  fi
}

#####################################################################################################################VDM
######################################## EDIT TRAEFIK
function traefik__TRuST__edit() {
  # check if traefik has been setup
  if [ ! -f "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/docker-compose.yml" ]; then
    showError "There is no ${VDM_CONTAINER_TYPE^} container to edit."
  else
    # give little warning for less command ready people
    if (whiptail --yesno "Only continue if you know what your doing!\n\n\
    ${USER^}, to save the changes you've made or to just close the file again press:\n\n\
      [ctrl+x] with nano on ubuntu." --title "Continue to edit ${VDM_CONTAINER_TYPE^} config." \
      --backtitle "${BACK_TITLE}" 15 112); then
      # lets open the file with nano for now
      "${EDITOR:-nano}" "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/docker-compose.yml" || return $?
      # if this container is enabled ask if it should be redeployed
      if (whiptail --yesno "Would you like to deploy or re-deploy the ${VDM_CONTAINER_TYPE^} container that you opened to edit?" \
        --title "Deploy or Re-Deploy Container" --backtitle "${BACK_TITLE}" 8 112); then
        # then we enable it
        enableContainer "${VDM_CONTAINER_TYPE}"
      fi
    fi
  fi
}

#####################################################################################################################VDM
######################################## EDIT PORTAINER
function portainer__TRuST__edit() {
  # check if portainer has been setup
  if [ ! -f "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/docker-compose.yml" ]; then
    showError "There is no ${VDM_CONTAINER_TYPE^} container to edit."
  else
    # give little warning for less command ready people
    if (whiptail --yesno "Only continue if you know what your doing!\n\n\
    ${USER^}, to save the changes you've made or to just close the file again press:\n\n\
      [ctrl+x] with nano on ubuntu." --title "Continue to edit ${VDM_CONTAINER_TYPE^} config." \
      --backtitle "${BACK_TITLE}" 15 112); then
      # lets open the file with nano for now
      "${EDITOR:-nano}" "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/docker-compose.yml" || return $?
      # if this container is enabled ask if it should be redeployed
      if (whiptail --yesno "Would you like to deploy or re-deploy the ${VDM_CONTAINER_TYPE^} container that you opened to edit?" \
        --title "Deploy or Re-Deploy Container" --backtitle "${BACK_TITLE}" 8 112); then
        # then we enable it
        enableContainer "${VDM_CONTAINER_TYPE}"
      fi
    fi
  fi
}

#####################################################################################################################VDM
######################################## ENABLE JOOMLA
# Save a generated Compose file atomically, leaving an existing setup intact
# when rendering, permission changes or the final rename fail.
function saveContainerCompose() {
  local generator="${1:-}"
  local compose_file="${2:-}"
  local compose_dir="${compose_file%/*}"
  local compose_tmp
  createPrivateDirectory -p "${compose_dir}" || return 1
  compose_tmp=$(mktemp "${compose_dir}/.docker-compose.XXXXXX") || return 1
  if ! "${generator}" >"${compose_tmp}" || ! chmod 600 "${compose_tmp}" ||
    ! mv -f "${compose_tmp}" "${compose_file}"; then
    rm -f "${compose_tmp}"
    showError "The Compose file (${compose_file}) could not be saved."
    return 1
  fi
}

# Run Compose exactly once with the selected environment. A failed operation must
# never be retried without its credentials or hidden by later filesystem changes.
function runContainerCompose() {
  local env_file="${1:-}"
  local compose_file="${2:-}"
  local compose_status=0
  shift 2
  if [ ! -f "${compose_file}" ]; then
    showError "The Compose file (${compose_file}) does not exist."
    return 1
  fi
  if [ -n "${env_file}" ]; then
    docker compose --env-file "${env_file}" --file "${compose_file}" "$@" || compose_status=$?
  else
    docker compose --file "${compose_file}" "$@" || compose_status=$?
  fi
  if [ "${compose_status}" -ne 0 ]; then
    showError "Docker Compose failed for (${compose_file}), exit status ${compose_status}.\n\nCheck the Docker output before trying again."
  fi
  return "${compose_status}"
}

function joomla__TRuST__enable() {
  if [ -n "${VDM_CONTAINER:-}" ] && ! isValidDomain "${VDM_CONTAINER}"; then
    showError "The container identifier (${VDM_CONTAINER}) is invalid."
    unset VDM_CONTAINER
    return 1
  fi
  # some local values
  local evn_file
  # check if this type have available containers
  if ! hasDirectories "${VDM_CONTAINER_TYPE}/available/"; then
    showError "The path ${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/available/ does not exist or is empty, first run a ${VDM_CONTAINER_TYPE^} setup."
    return 1
  elif [ ! -d "${VDM_PROJECT_PATH}" ]; then
    # this should never happen, but in case
    showError "The path ${VDM_PROJECT_PATH} does not exist, so we can't mount the persistent volumes. This error should never show, \
      please open an issue and report octojoom-error-1234 with the steps of how you got here?"
    return 1
  elif [ ${#VDM_CONTAINER} -ge 1 ]; then
    # this means we have a single already selected container to enable if it exists
    if [ -d "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/available/${VDM_CONTAINER}" ]; then
      # create the folder as needed
      mkdir -p "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/enabled/" || return $?
      # create the soft link
      [ -e "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/enabled/${VDM_CONTAINER}" ] || {
        ln -s "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/available/${VDM_CONTAINER}" "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/enabled/${VDM_CONTAINER}" || return $?
      }
      # set some local variables
      local evn_file
      # check if image has its own env file also
      evn_file=''
      # shellcheck disable=SC2015
      [ -f "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/enabled/${VDM_CONTAINER}/.env" ] && evn_file="${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/enabled/${VDM_CONTAINER}/.env" || {
        [ -f "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/.env" ] && evn_file="${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/.env"
      }
      # make sure the docker image is started
      runContainerCompose "${evn_file}" "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/enabled/${VDM_CONTAINER}/docker-compose.yml" up -d || {
        local compose_status=$?
        unset VDM_CONTAINER
        return "${compose_status}"
      }
    else
      showError "The (${VDM_CONTAINER}) container does not exist."
      unset VDM_CONTAINER
      return 1
    fi
    # always unset after
    VDM_CONTAINER=''
    unset VDM_CONTAINER
  else
    # set some local variables
    local vdm_enable_me
    local container
    local evn_file
    # create the folder as needed
    mkdir -p "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/enabled/" || return $?
    # get containers to enable
    vdm_enable_me=$(getSelectedDirectories "Select container/s to enable." \
      "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/available/" "Enable ${VDM_CONTAINER_TYPE^} Containers")
    # check that we have something, else return to main menu
    if [ ${#vdm_enable_me} -ge 1 ]; then
      # convert the string to and array
      IFS=' ' read -r -a vdm_enable_me_array <<<"${vdm_enable_me[@]}"
      # loop over the directories to build the
      for containered in "${vdm_enable_me_array[@]}"; do
        # remove the " from the string
        container="${containered//\"/}"
        # create the soft link
        [ -e "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/enabled/${container}" ] || {
          ln -s "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/available/${container}" "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/enabled/${container}" || return $?
        }
        # check if image has its own env file also
        evn_file=''
        # shellcheck disable=SC2015
        [ -f "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/enabled/${container}/.env" ] && evn_file="${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/enabled/${container}/.env" || {
          [ -f "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/.env" ] && evn_file="${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/.env"
        }
        # make sure the docker image is started
        runContainerCompose "${evn_file}" "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/enabled/${container}/docker-compose.yml" up -d || return $?
      done
    fi
  fi
}

#####################################################################################################################VDM
######################################## ENABLE OPENSSH
function openssh__TRuST__enable() {
  if [ -n "${VDM_CONTAINER:-}" ] && ! isValidDomain "${VDM_CONTAINER}"; then
    showError "The container identifier (${VDM_CONTAINER}) is invalid."
    unset VDM_CONTAINER
    return 1
  fi
  # check if this type have available containers
  if ! hasDirectories "${VDM_CONTAINER_TYPE}/available/"; then
    showError "The path ${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/available/ does not exist, first run a ${VDM_CONTAINER_TYPE} setup."
    return 1
  elif [ ${#VDM_CONTAINER} -ge 1 ]; then
    # this means we have a single already selected container to enable if it exists
    if [ -d "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/available/${VDM_CONTAINER}" ]; then
      # create the folder as needed
      mkdir -p "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/enabled/" || return $?
      # create the soft lin
      [ -e "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/enabled/${VDM_CONTAINER}" ] || {
        ln -s "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/available/${VDM_CONTAINER}" "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/enabled/${VDM_CONTAINER}" || return $?
      }
      # set some local variables
      local evn_file
      # check if image has its own env file also
      evn_file=''
      # shellcheck disable=SC2015
      [ -f "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/enabled/${VDM_CONTAINER}/.env" ] && evn_file="${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/enabled/${VDM_CONTAINER}/.env" || {
        [ -f "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/.env" ] && evn_file="${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/.env"
      }
      # make sure the docker image is started
      runContainerCompose "${evn_file}" "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/enabled/${VDM_CONTAINER}/docker-compose.yml" up -d || {
        local compose_status=$?
        unset VDM_CONTAINER
        return "${compose_status}"
      }
    else
      showError "The (${VDM_CONTAINER}) container does not exist."
      unset VDM_CONTAINER
      return 1
    fi
    # always unset after
    VDM_CONTAINER=''
    unset VDM_CONTAINER
  else
    # set some local variables
    local vdm_enable_me
    local container
    local evn_file
    # create the folder as needed
    mkdir -p "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/enabled/" || return $?
    # get containers to enable
    vdm_enable_me=$(getSelectedDirectories "Select container/s to enable." \
      "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/available/" "Enable ${VDM_CONTAINER_TYPE^} Containers")
    # check that we have something, else return to main menu
    if [ ${#vdm_enable_me} -ge 1 ]; then
      # convert the string to and array
      IFS=' ' read -r -a vdm_enable_me_array <<<"${vdm_enable_me[@]}"
      # loop over the directories to build the
      for containered in "${vdm_enable_me_array[@]}"; do
        # remove the " from the string
        container="${containered//\"/}"
        # create the soft link
        [ -e "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/enabled/${container}" ] || {
          ln -s "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/available/${container}" "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/enabled/${container}" || return $?
        }
        # check if image has its own env file also
        evn_file=''
        # shellcheck disable=SC2015
        [ -f "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/enabled/${container}/.env" ] && evn_file="${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/enabled/${container}/.env" || {
          [ -f "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/.env" ] && evn_file="${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/.env"
        }
        # make sure the docker image is started
        runContainerCompose "${evn_file}" "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/enabled/${container}/docker-compose.yml" up -d || return $?
      done
    fi
  fi
}

#####################################################################################################################VDM
######################################## ENABLE TRAEFIK
function traefik__TRuST__enable() {
  # check if traefik has been setup
  if [ ! -f "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/docker-compose.yml" ]; then
    showError "There is no ${VDM_CONTAINER_TYPE^} container to enable, first run the ${VDM_CONTAINER_TYPE^} setup."
    return 1
  elif ensurePortsFree; then
    # set some local variables
    local evn_file
    # check if image has its own env file also
    evn_file=''
    # shellcheck disable=SC2015
    [ -f "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/.env" ] && evn_file="${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/.env" || {
      [ -f "${VDM_SRC_PATH}/.env" ] && evn_file="${VDM_SRC_PATH}/.env"
    }
    # make sure the docker image is started
    runContainerCompose "${evn_file}" "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/docker-compose.yml" up -d || return $?
  else
    return 1
  fi
}

#####################################################################################################################VDM
######################################## ENABLE PORTAINER
function portainer__TRuST__enable() {
  # check if traefik has been setup
  if [ ! -f "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/docker-compose.yml" ]; then
    showError "There is no ${VDM_CONTAINER_TYPE^} container to enable, first run the ${VDM_CONTAINER_TYPE^} setup."
    return 1
  else
    # set some local variables
    local evn_file
    # check if image has its own env file also
    evn_file=''
    # shellcheck disable=SC2015
    [ -f "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/.env" ] && evn_file="${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/.env" || {
      [ -f "${VDM_SRC_PATH}/.env" ] && evn_file="${VDM_SRC_PATH}/.env"
    }
    # make sure the docker image is started
    runContainerCompose "${evn_file}" "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/docker-compose.yml" up -d || return $?
  fi
}

#####################################################################################################################VDM
######################################## DISABLE JOOMLA
function joomla__TRuST__disable() {
  if [ -n "${VDM_CONTAINER:-}" ] && ! isValidDomain "${VDM_CONTAINER}"; then
    showError "The container identifier (${VDM_CONTAINER}) is invalid."
    unset VDM_CONTAINER
    return 1
  fi
  # check if this type has enabled containers
  if ! hasDirectories "${VDM_CONTAINER_TYPE}/enabled/"; then
    showError "There are no ${VDM_CONTAINER_TYPE^} containers to disable."
  elif [ ${#VDM_CONTAINER} -ge 1 ]; then
    # this means we have a single already selected container to disable if it exists
    if [ -d "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/enabled/${VDM_CONTAINER}" ]; then
      # set some local variables
      local evn_file
      # check if image has its own env file also
      evn_file=''
      # shellcheck disable=SC2015
      [ -f "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/enabled/${VDM_CONTAINER}/.env" ] && evn_file="${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/enabled/${VDM_CONTAINER}/.env" || {
        [ -f "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/.env" ] && evn_file="${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/.env"
      }
      # make sure the docker image is stopped
      runContainerCompose "${evn_file}" "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/enabled/${VDM_CONTAINER}/docker-compose.yml" down --remove-orphans || {
        local compose_status=$?
        unset VDM_CONTAINER
        return "${compose_status}"
      }
      # then remove soft link
      rm -rf "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/enabled/${VDM_CONTAINER}" || return $?
    else
      showError "The (${VDM_CONTAINER}) container is not enabled."
    fi
    # always unset after
    VDM_CONTAINER=''
    unset VDM_CONTAINER
  else
    # set some local variables
    local vdm_disable_me
    local container
    local evn_file
    # get containers to enable
    vdm_disable_me=$(getSelectedDirectories "Select container/s to disable." \
      "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/enabled/" "Disable ${VDM_CONTAINER_TYPE^} Containers")
    # check that we have something, else return to main menu
    if [ ${#vdm_disable_me} -ge 1 ]; then
      # convert the string to and array
      IFS=' ' read -r -a vdm_disable_me_array <<<"${vdm_disable_me[@]}"
      # loop over the directories to build the
      for containered in "${vdm_disable_me_array[@]}"; do
        # remove the " from the string
        container="${containered//\"/}"
        # check if image has its own env file also
        evn_file=''
        # shellcheck disable=SC2015
        [ -f "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/enabled/${container}/.env" ] && evn_file="${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/enabled/${container}/.env" || {
          [ -f "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/.env" ] && evn_file="${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/.env"
        }
        # make sure the docker image is stopped
        runContainerCompose "${evn_file}" "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/enabled/${container}/docker-compose.yml" down --remove-orphans || return $?
        # then remove soft link
        rm -rf "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/enabled/${container}" || return $?
      done
    fi
  fi
}

#####################################################################################################################VDM
######################################## DISABLE OPENSSH
function openssh__TRuST__disable() {
  if [ -n "${VDM_CONTAINER:-}" ] && ! isValidDomain "${VDM_CONTAINER}"; then
    showError "The container identifier (${VDM_CONTAINER}) is invalid."
    unset VDM_CONTAINER
    return 1
  fi
  # check if this type has enabled containers
  if ! hasDirectories "${VDM_CONTAINER_TYPE}/enabled/"; then
    showError "There are no ${VDM_CONTAINER_TYPE^} containers to disable."
  elif [ ${#VDM_CONTAINER} -ge 1 ]; then
    # this means we have a single already selected container to disable if it exists
    if [ -d "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/enabled/${VDM_CONTAINER}" ]; then
      # set some local variables
      local evn_file
      # check if image has its own env file also
      evn_file=''
      # shellcheck disable=SC2015
      [ -f "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/enabled/${VDM_CONTAINER}/.env" ] && evn_file="${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/enabled/${VDM_CONTAINER}/.env" || {
        [ -f "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/.env" ] && evn_file="${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/.env"
      }
      # make sure the docker image is stopped
      runContainerCompose "${evn_file}" "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/enabled/${VDM_CONTAINER}/docker-compose.yml" down --remove-orphans || {
        local compose_status=$?
        unset VDM_CONTAINER
        return "${compose_status}"
      }
      # then remove soft link
      rm -rf "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/enabled/${VDM_CONTAINER}" || return $?
    else
      showError "The (${VDM_CONTAINER}) container is not enabled."
    fi
    # always unset after
    VDM_CONTAINER=''
    unset VDM_CONTAINER
  else
    # set some local variables
    local vdm_disable_me
    local container
    local evn_file
    # get containers to enable
    vdm_disable_me=$(getSelectedDirectories "Select container/s to disable." \
      "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/enabled/" "Disable ${VDM_CONTAINER_TYPE^} Containers")
    # check that we have something, else return to main menu
    if [ ${#vdm_disable_me} -ge 1 ]; then
      # convert the string to and array
      IFS=' ' read -r -a vdm_disable_me_array <<<"${vdm_disable_me[@]}"
      # loop over the directories to build the
      for containered in "${vdm_disable_me_array[@]}"; do
        # remove the " from the string
        container="${containered//\"/}"
        # check if image has its own env file also
        evn_file=''
        # shellcheck disable=SC2015
        [ -f "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/enabled/${container}/.env" ] && evn_file="${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/enabled/${container}/.env" || {
          [ -f "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/.env" ] && evn_file="${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/.env"
        }
        # make sure the docker image is stopped
        runContainerCompose "${evn_file}" "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/enabled/${container}/docker-compose.yml" down --remove-orphans || return $?
        # then remove soft link
        rm -rf "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/enabled/${container}" || return $?
      done
    fi
  fi
}

#####################################################################################################################VDM
######################################## DISABLE TRAEFIK
function traefik__TRuST__disable() {
  # check if traefik has been setup
  if [ ! -f "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/docker-compose.yml" ]; then
    showError "There is no ${VDM_CONTAINER_TYPE^} container to disable."
  else
    # set some local variables
    local evn_file
    # check if image has its own env file also
    evn_file=''
    # shellcheck disable=SC2015
    [ -f "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/.env" ] && evn_file="${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/.env" || {
      [ -f "${VDM_SRC_PATH}/.env" ] && evn_file="${VDM_SRC_PATH}/.env"
    }
    # make sure the docker image is stopped
    runContainerCompose "${evn_file}" "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/docker-compose.yml" down || return $?
  fi
}

#####################################################################################################################VDM
######################################## DISABLE PORTAINER
function portainer__TRuST__disable() {
  # check if portainer has been setup
  if [ ! -f "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/docker-compose.yml" ]; then
    showError "There is no ${VDM_CONTAINER_TYPE^} container to disable."
  else
    # set some local variables
    local evn_file
    # check if image has its own env file also
    evn_file=''
    # shellcheck disable=SC2015
    [ -f "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/.env" ] && evn_file="${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/.env" || {
      [ -f "${VDM_SRC_PATH}/.env" ] && evn_file="${VDM_SRC_PATH}/.env"
    }
    # make sure the docker image is stopped
    runContainerCompose "${evn_file}" "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/docker-compose.yml" down || return $?
  fi
}

#####################################################################################################################VDM
######################################## UP JOOMLA
function joomla__TRuST__up() {
  # check if this type has enabled containers
  if ! hasDirectories "${VDM_CONTAINER_TYPE}/enabled/"; then
    showError "There are no ${VDM_CONTAINER_TYPE^} containers enabled, first enable some containers.\n\
      (UP and DOWN targets only enabled containers)"
  else
    # set some local variables
    local evn_file
    local vdm_container
    # get all zip files
    for yml in "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/enabled/"*/*.yml; do
      # get the vdm_container value
      vdm_container="${yml%/docker-compose.yml}"
      # check if image has its own env file also
      evn_file=''
      # check if image has its own env file also
      # shellcheck disable=SC2015
      [ -f "${vdm_container}/.env" ] && evn_file="${vdm_container}/.env" || {
        [ -f "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/.env" ] && evn_file="${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/.env"
      }
      # make sure the docker image is started
      runContainerCompose "${evn_file}" "${yml}" up -d || return $?
    done
  fi
}

#####################################################################################################################VDM
######################################## UP OPENSSH
function openssh__TRuST__up() {
  # check if this type has enabled containers
  if ! hasDirectories "${VDM_CONTAINER_TYPE}/enabled/"; then
    showError "There are no ${VDM_CONTAINER_TYPE^} containers enabled, first enable some containers.\n\
      (UP and DOWN targets only enabled containers)"
  else
    # set some local variables
    local evn_file
    local vdm_container
    # get all zip files
    for yml in "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/enabled/"*/*.yml; do
      # get the vdm_container value
      vdm_container="${yml%/docker-compose.yml}"
      # check if image has its own env file also
      evn_file=''
      # check if image has its own env file also
      # shellcheck disable=SC2015
      [ -f "${vdm_container}/.env" ] && evn_file="${vdm_container}/.env" || {
        [ -f "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/.env" ] && evn_file="${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/.env"
      }
      # make sure the docker image is started
      runContainerCompose "${evn_file}" "${yml}" up -d || return $?
    done
  fi
}

#####################################################################################################################VDM
######################################## DOWN JOOMLA
function joomla__TRuST__down() {
  # check if this type has enabled containers
  if ! hasDirectories "${VDM_CONTAINER_TYPE}/enabled/"; then
    showError "There are no ${VDM_CONTAINER_TYPE^} containers to take down.\n\
      (UP and DOWN targets only enabled containers)"
    return 1
  elif getInputYesNo "Are you absolutely sure you want to take down all the ${VDM_CONTAINER_TYPE^} containers?" \
      "Take Down Containers" 8 112; then
    # get all zip files
    for yml in "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/enabled/"*/*.yml; do
      # get the vdm_container value
      vdm_container="${yml%/docker-compose.yml}"
      # check if image has its own env file also
      evn_file=''
      # check if image has its own env file also
      # shellcheck disable=SC2015
      [ -f "${vdm_container}/.env" ] && evn_file="${vdm_container}/.env" || {
        [ -f "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/.env" ] && evn_file="${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/.env"
      }
      # make sure the docker image is started
      runContainerCompose "${evn_file}" "${yml}" down || return $?
    done
  else
    return 1
  fi
}

#####################################################################################################################VDM
######################################## DOWN OPENSSH
function openssh__TRuST__down() {
  # check if this type has enabled containers
  if ! hasDirectories "${VDM_CONTAINER_TYPE}/enabled/"; then
    showError "There are no ${VDM_CONTAINER_TYPE^} containers to take down."
    return 1
  elif getInputYesNo "Are you absolutely sure you want to take down all the ${VDM_CONTAINER_TYPE^} containers?" \
      "Take Down Containers" 8 112; then
    # get all zip files
    for yml in "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/enabled/"*/*.yml; do
      # get the vdm_container value
      vdm_container="${yml%/docker-compose.yml}"
      # check if image has its own env file also
      evn_file=''
      # check if image has its own env file also
      # shellcheck disable=SC2015
      [ -f "${vdm_container}/.env" ] && evn_file="${vdm_container}/.env" || {
        [ -f "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/.env" ] && evn_file="${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/.env"
      }
      # make sure the docker image is started
      runContainerCompose "${evn_file}" "${yml}" down || return $?
    done
  else
    return 1
  fi
}

#####################################################################################################################VDM
######################################## CLONE JOOMLA PROJECT FILES
function joomla__TRuST__clonefiles() {
  # check if we have persistent volumes (project folders) to clone
  if ! hasDirectories '' "${VDM_PROJECT_PATH}"; then
    showError "There are no project folders found in ${VDM_PROJECT_PATH}."
  elif getInputYesNo "This only copies a project folder (persistent volume) found in (${VDM_PROJECT_PATH}) to a new folder.\n\
It does not create a docker-compose.yml file, and the copied Joomla site keeps pointing at the original database.\n\
Use (Clone a container) to clone a complete container.\n\nWould you like to continue?" \
      "Clone Project Files" 14 112; then
    # trigger the volumes clone script
    clonePersistentVolume
  fi
}

#####################################################################################################################VDM
######################################## CLONE JOOMLA
function joomla__TRuST__clone() {
  local clone_status=0
  # check if this type have available containers
  if ! hasDirectories "${VDM_CONTAINER_TYPE}/available/"; then
    showError "The path ${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/available/ does not exist or is empty, first run a ${VDM_CONTAINER_TYPE^} setup."
    return 1
  elif ! hasDirectories '' "${VDM_PROJECT_PATH}"; then
    showError "There are no project folders (persistent volumes) found in ${VDM_PROJECT_PATH}."
    return 1
  else
    # run the clone
    cloneJoomlaContainer || clone_status=$?
    ##########################
    ### unset all no longer needed (so a setup in the same session asks again)
    unset VDM_SUBDOMAIN
    unset VDM_KEY
    unset VDM_ENV_KEY
    unset VDM_SRC_KEY
    unset VDM_SRC_ENV_KEY
    unset VDM_SRC_PROJECT_FOLDER
    unset VDM_SRC_MAILCATCHER
    unset VDM_SRC_NAMED_VOLUMES
    unset VDM_SRC_SECURE
  fi
  # return a success
  return "${clone_status}"
}

# clone a complete Joomla container: docker-compose.yml, env values and project folder
# Only namespace values change (key, env key, sub-domain, domain); the database name,
# users, passwords and table prefix are copied as they are. The clone is placed in
# available/ and is NOT enabled.
function cloneJoomlaContainer() {
  local clone_lock="${VDM_REPO_PATH}/joomla/.clone.lock"
  local clone_status=0
  if ! mkdir "${clone_lock}" 2>/dev/null; then
    showError "A clone is already running, or an interrupted clone left ${clone_lock}.\n\nVerify that no clone is running before removing that lock directory."
    return 1
  fi
  cloneJoomlaContainerUnlocked || clone_status=$?
  if ! rmdir "${clone_lock}"; then
    showError "The clone lock (${clone_lock}) could not be released."
    return 1
  fi
  return "${clone_status}"
}

# The wrapper serializes the source stop/copy/restart cycle across clones.
function cloneJoomlaContainerUnlocked() {
  # set some local variables
  local container
  local old_key
  local old_env
  local old_sub
  local old_domain
  local src_dir
  local src_yml
  local src_env_file
  local shared_env
  local per_container_env=false
  local project
  local config
  local host
  local patch_host=true
  local current_site_name
  local site_name=''
  local source_running=false
  local new_env
  local new_container
  local new_dir
  local new_yml
  local new_project
  local env_target
  local env_added=''
  local project_created=false
  local env_file
  local validation
  local needed
  local available
  local copy_status
  local scheme='http://'
  local stop_line=''
  local warnings=''
  local message
  local rc
  local host_conflict
  local host_suffix
  local shared_note=''
  local copy_pid
  local source_state=0
  local restart_status=0
  ##########################
  ### 1. select the source container
  container=$(getSelectedDirectory "Select the container you would like to clone." \
    "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/available/" '' "Clone ${VDM_CONTAINER_TYPE^} Container") || return 0
  # check that we have something, else return to main menu
  [ ${#container} -ge 1 ] || return 0
  isValidDomain "${container}" || return 1
  src_dir="${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/available/${container}"
  src_yml="${src_dir}/docker-compose.yml"
  if [ ! -f "${src_yml}" ]; then
    showError "The (${container}) container has no docker-compose.yml file to clone."
    return 1
  fi
  ##########################
  ### 2. read the identity of the source from its docker-compose.yml
  if ! getJoomlaComposeIdentity "${src_yml}"; then
    showError "The docker-compose.yml of (${container}) does not follow the ${PROGRAM_NAME} layout\n\
(no mariadb<key> container name or VDM_<ENV_KEY>_DB variable found).\n\n\
It was probably written by hand, so it must also be cloned by hand." 12
    return 1
  fi
  old_key="${VDM_SRC_KEY}"
  old_env="${VDM_SRC_ENV_KEY}"
  old_sub="${container%%.*}"
  old_domain="${container#*.}"
  if ${VDM_SRC_NAMED_VOLUMES}; then
    showError "The (${container}) container keeps its files in named docker volumes instead of a project folder.\n\n\
Cloning named volumes is not supported yet." 10
    return 1
  fi
  # older compose files behind Cloudflare have no certificate resolver, so the global switch also counts
  if ${VDM_SRC_SECURE} || [ "${VDM_SECURE:-false}" = "true" ]; then
    scheme='https://'
  fi
  # the env file the source uses (a per-container .env wins over the shared one)
  shared_env="${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/.env"
  [ -f "${src_dir}/.env" ] && per_container_env=true
  src_env_file=$(getContainerEnvFile "${VDM_CONTAINER_TYPE}" "${container}" 'available')
  if [ ${#src_env_file} -lt 1 ]; then
    showError "No .env file was found for (${container}), neither ${src_dir}/.env nor ${shared_env}.\n\n\
The clone needs the env values of the source container."
    return 1
  fi
  ##########################
  ### 3. select the project folder (persistent volume) of the source
  project=$(getSelectedDirectory "Select the project folder (persistent volume) of the (${container}) container.\n\
[The folder named in its docker-compose.yml is pre-selected]" \
    "${VDM_PROJECT_PATH}" "${VDM_SRC_PROJECT_FOLDER}" "Select Project Folder") || return 0
  if ! isSafeProjectName "${project}" || [ -L "${VDM_PROJECT_PATH}/${project}" ]; then
    showError "Select a direct project directory to clone."
    return 1
  fi
  if [ ${#project} -lt 1 ] || [ ! -d "${VDM_PROJECT_PATH}/${project}/joomla" ] || [ ! -d "${VDM_PROJECT_PATH}/${project}/db" ]; then
    showError "The (${project}) folder is not a Joomla project folder, it must have a joomla and a db sub-folder."
    return 1
  fi
  if [ -n "${VDM_SRC_PROJECT_FOLDER}" ] && [ "${project}" != "${VDM_SRC_PROJECT_FOLDER}" ] &&
    ! getInputYesNo "The docker-compose.yml of (${container}) mounts the (${VDM_SRC_PROJECT_FOLDER}) project folder, but you selected (${project}).\n\n\
The clone will be a copy of (${project}). Would you like to continue?" "Different Project Folder" 12 112 "defaultno"; then
    return 0
  fi
  config="${VDM_PROJECT_PATH}/${project}/joomla/configuration.php"
  if [ ! -f "${config}" ]; then
    showError "The (${project}) project has no joomla/configuration.php file, so Joomla is not installed yet.\n\n\
Setup a new container instead of cloning this one."
    return 1
  fi
  ##########################
  ### 4. make sure the site uses the database of the container being cloned
  host=$(getJoomlaConfigValue "${config}" 'host')
  if ! [[ "${host}" =~ ^mariadb${old_key}(:[0-9]+)?$ ]]; then
    if ! getInputYesNo "The configuration.php of (${project}) connects to the database host (${host}) and not to (mariadb${old_key}).\n\n\
The clone would keep using that same database, which is only safe when it is not the database of another container.\n\n\
Would you like to continue without changing the database host?" "Database Host Mismatch" 14 112 "defaultno"; then
      return 0
    fi
    patch_host=false
  fi
  ##########################
  ### 5. get the new key (container names and project folder)
  while true; do
    setUniqueKey "Enter a new key for the clone of (${container}).\nIt is used for the container names and the project folder name." || return $?
    if [ "${VDM_KEY}" = "${old_key}" ]; then
      showError "The key (${VDM_KEY}) is the key of the container being cloned, select another."
    else
      rc=0
      isJoomlaKeyInUse "${VDM_KEY}" || rc=$?
      case "${rc}" in
      0) showError "The key (${VDM_KEY}) is already used by another container or project folder, select another." ;;
      1) break ;;
      *)
        showError "The existing containers could not be inspected safely. The clone was cancelled without changing any files."
        return 1
        ;;
      esac
    fi
    unset VDM_KEY
  done
  ##########################
  ### 6. get the new env key
  while true; do
    setEnvironmentKey || return $?
    new_env="${VDM_ENV_KEY^^}"
    if ! ${per_container_env} && [ "${new_env}" != "${old_env}" ] && hasContainerEnvVariables "${shared_env}" "${new_env}"; then
      showError "The environment key (${new_env}) already has values in ${shared_env}, select another."
      unset VDM_ENV_KEY
    else
      break
    fi
  done
  ##########################
  ### 7. get the domain and the new sub-domain (none of the clone's hosts may be used by another container)
  setDomain || return $?
  while true; do
    setSubDomain "${VDM_KEY,,}" "joomla" || return $?
    host_conflict=''
    for host_suffix in '' 'db' 'mail'; do
      if isJoomlaHostInUse "${VDM_SUBDOMAIN}${host_suffix}.${VDM_DOMAIN}"; then
        host_conflict="${VDM_SUBDOMAIN}${host_suffix}.${VDM_DOMAIN}"
        break
      fi
    done
    [ -z "${host_conflict}" ] && break
    showError "The host (${host_conflict}) is already used by another container, select another sub-domain."
    unset VDM_SUBDOMAIN
  done
  new_container="${VDM_SUBDOMAIN}.${VDM_DOMAIN}"
  new_dir="${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/available/${new_container}"
  new_yml="${new_dir}/docker-compose.yml"
  new_project="${VDM_PROJECT_PATH}/${VDM_KEY}"
  if ${per_container_env}; then
    env_target="${new_dir}/.env"
  else
    env_target="${shared_env}"
  fi
  ##########################
  ### 8. only in expert mode ask for a new site name
  if isExpert && ${patch_host}; then
    current_site_name=$(getJoomlaConfigValue "${config}" 'sitename')
    site_name=$(getInput "Enter the site name of the clone.\n[Keep the current name (${current_site_name}) to leave it unchanged]" \
      "${current_site_name} (clone)" 'Enter Site Name')
    [ "${site_name}" = "${current_site_name}" ] && site_name=''
  fi
  ##########################
  ### 9. check if the source is running (an enabled source is stopped during the copy)
  isContainerRunning "mariadb${old_key}" || source_state=$?
  if [ "${source_state}" -gt 1 ]; then
    showError "Docker could not inspect the source database. The clone was cancelled without changing any files."
    return 1
  fi
  if [ "${source_state}" -eq 0 ]; then
    if [ -d "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/enabled/${container}" ]; then
      source_running=true
      stop_line="The (${container}) containers will be stopped during the copy and started again afterwards.\n"
    elif getInputYesNo "The database container (mariadb${old_key}) is running, but (${container}) is not enabled,\n\
so it was started outside ${PROGRAM_NAME} and cannot be stopped for the copy.\n\n\
Copying a running database can produce an inconsistent copy. Stop it first, or continue at your own risk.\n\n\
Would you like to continue anyway?" "Database Is Running" 14 112 "defaultno"; then
      warnings+="  - The database of (${container}) was copied while it was running, check the clone's data.\n"
    else
      showNotice "The clone was cancelled, nothing was changed." 8
      return 0
    fi
  fi
  ##########################
  ### 10. confirm the plan (nothing has been written yet)
  message="You are about to clone the (${container}) container.\n\n"
  message+=$(printf '  %-18s %-28s %s' '' 'FROM' 'TO')"\n"
  message+=$(printf '  %-18s %-28s %s' 'Key:' "${old_key}" "${VDM_KEY}")"\n"
  message+=$(printf '  %-18s %-28s %s' 'Env key:' "VDM_${old_env}_*" "VDM_${new_env}_*")"\n"
  message+=$(printf '  %-18s %-28s %s' 'Site:' "${container}" "${new_container}")"\n"
  message+=$(printf '  %-18s %-28s %s' 'Project folder:' "${project}" "${VDM_KEY}")"\n"
  if ${patch_host}; then
    message+=$(printf '  %-18s %-28s %s' 'Database host:' "mariadb${old_key}" "mariadb${VDM_KEY} (patched in configuration.php)")"\n"
  else
    message+=$(printf '  %-18s %-28s %s' 'Database host:' "${host}" "${host} (NOT changed)")"\n"
  fi
  [ -n "${site_name}" ] && message+=$(printf '  %-18s %-28s %s' 'Site name:' "${current_site_name}" "${site_name}")"\n"
  if ! ${per_container_env} && [ "${old_env}" = "${new_env}" ]; then
    shared_note=" (shared with ${container})"
  fi
  message+="\nThis will create:\n  ${new_yml}\n  ${new_project}  (a full copy of ${project})\n"
  message+="  VDM_${new_env}_* values${shared_note} in ${env_target}\n\n"
  message+="${stop_line}"
  message+="The database name, users, passwords and table prefix stay exactly as they are.\nThe clone is placed in available/ and is not enabled.\n\nContinue?"
  if [ "${VDM_FORCE:-false}" != "true" ] &&
    ! whiptail --yesno "${message}" "$(getDialogHeight "${message}" 7)" 112 --scrolltext \
      --title "Confirm Clone" --backtitle "${BACK_TITLE}" 3>&1 1>&2 2>&3; then
    showNotice "The clone was cancelled, nothing was changed." 8
    return 0
  fi
  ##########################
  ### 11. we need sudo for the copy (db files are owned by the database user), where sudo is used
  if useSudo; then
    if ! getInputYesNo "${USER^}, to copy the project folder and update its configuration.php we need sudo privileges." \
        "Give sudo Privileges" 8 112; then
      showNotice "The clone was cancelled, nothing was changed." 8
      return 0
    fi
    if ! sudo -v; then
      showError "The clone needs sudo privileges to copy the project folder, nothing was changed."
      return 1
    fi
  fi
  ##########################
  ### 12. make sure there is enough free space for the copy
  needed=$(runPrivileged du -sk "${VDM_PROJECT_PATH}/${project}" 2>/dev/null | cut -f1)
  available=$(df -Pk "${VDM_PROJECT_PATH}" 2>/dev/null | awk 'NR==2 {print $4}')
  if [[ "${needed}" =~ ^[0-9]+$ ]] && [[ "${available}" =~ ^[0-9]+$ ]] && [ "${needed}" -gt "${available}" ]; then
    showError "Not enough free space in ${VDM_PROJECT_PATH}.\n\n\
The (${project}) folder needs $((needed / 1024)) MB but only $((available / 1024)) MB are free. Nothing was changed."
    return 1
  fi
  ##########################
  ### 13. the env values of the clone
  createPrivateDirectory "${new_dir}" || return 1
  if ${per_container_env}; then
    if ! cloneContainerEnvFile "${src_dir}/.env" "${env_target}" "${old_env}" "${new_env}"; then
      showError "The env file ${env_target} could not be written, nothing was changed."
      cloneJoomlaRollback "${new_dir}" '' false "${shared_env}" ''
      return 1
    fi
  elif [ "${old_env}" != "${new_env}" ]; then
    if ! env_added=$(cloneContainerEnvVariables "${shared_env}" "${old_env}" "${new_env}"); then
      showError "The VDM_${new_env}_* values could not be added to ${shared_env}, nothing was changed."
      cloneJoomlaRollback "${new_dir}" '' false "${shared_env}" "${env_added}"
      return 1
    fi
  fi
  ##########################
  ### 14. the docker-compose.yml of the clone
  rc=0
  rewriteJoomlaComposeIdentity "${src_yml}" "${new_yml}" "${old_key}" "${VDM_KEY}" "${old_env}" "${new_env}" \
    "${old_sub}" "${VDM_SUBDOMAIN}" "${old_domain}" "${VDM_DOMAIN}" "${VDM_SRC_PROJECT_FOLDER}" || rc=$?
  if [ "${rc}" -ne 0 ]; then
    if [ "${rc}" -eq 2 ]; then
      showError "The docker-compose.yml of (${container}) has a value the clone cannot rename safely\n\
(a container name, host, mount or env variable that still points at the source), so the clone was rolled back.\n\n\
This happens when the file was edited by hand. Clone it by hand, or open an issue and report\n\
octojoom-clone-error-2 with a copy of the docker-compose.yml." 14
    else
      showError "The docker-compose.yml of the clone could not be written, so the clone was rolled back."
    fi
    cloneJoomlaRollback "${new_dir}" '' false "${shared_env}" "${env_added}"
    return 1
  fi
  if ! chmod 600 "${new_yml}"; then
    cloneJoomlaRollback "${new_dir}" '' false "${shared_env}" "${env_added}"
    showError "The permissions of the cloned Compose file could not be secured."
    return 1
  fi
  ##########################
  ### 15. let docker compose validate the new file (with the env file the clone will use)
  env_file=$(getContainerEnvFile "${VDM_CONTAINER_TYPE}" "${new_container}" 'available')
  if command -v docker >/dev/null 2>&1; then
    if [ ${#env_file} -ge 1 ]; then
      validation=$(docker compose --env-file "${env_file}" --file "${new_yml}" config -q 2>&1)
    else
      validation=$(docker compose --file "${new_yml}" config -q 2>&1)
    fi
    # shellcheck disable=SC2181
    if [ $? -ne 0 ]; then
      showError "docker compose rejected the docker-compose.yml of the clone, so the clone was rolled back:\n\n${validation}" 20
      cloneJoomlaRollback "${new_dir}" '' false "${shared_env}" "${env_added}"
      return 1
    fi
  fi
  ##########################
  ### 16. stop the source containers so the database files are copied in a consistent state
  if ${source_running}; then
    echo "Stopping the (${container}) containers for the copy, please wait..."
    if ! composeSourceContainer "${container}" 'stop' ||
      { isContainerRunning "mariadb${old_key}"; [ $? -ne 1 ]; }; then
      # some containers may already be stopped, so we start them all again
      echo "Starting the (${container}) containers again..."
      if composeSourceContainer "${container}" 'start'; then
        showError "The (${container}) containers could not be stopped cleanly, so the clone was rolled back.\n\n\
They were started again, nothing was changed."
      else
        showError "The (${container}) containers could not be stopped cleanly, so the clone was rolled back.\n\n\
They could also not be started again: use (Enable existing container) or (Pull up all enabled containers)\n\
to start (${container}) again." 12
      fi
      cloneJoomlaRollback "${new_dir}" '' false "${shared_env}" "${env_added}"
      return 1
    fi
  fi
  ##########################
  ### 17. copy the project folder (including hidden files, keeping owners and permissions)
  if ! mkdir "${new_project}"; then
    if ${source_running}; then
      composeSourceContainer "${container}" 'start' || showError "The source containers could not be restarted. Start (${container}) from the menu."
    fi
    cloneJoomlaRollback "${new_dir}" '' false "${shared_env}" "${env_added}"
    showError "The clone project directory could not be created."
    return 1
  fi
  project_created=true
  rm -f "${VDM_SRC_PATH}/.clone_status"
  progressSwitchOn
  {
    runPrivileged cp -a "${VDM_PROJECT_PATH}/${project}/." "${new_project}/" 2>"${VDM_SRC_PATH}/.clone_error"
    echo $? >"${VDM_SRC_PATH}/.clone_status"
    progressSwitchOff
  } &
  copy_pid=$!
  showProgress "Copying the (${project}) project folder to (${VDM_KEY}).\n(cp -a ${project}/. ${VDM_KEY}/)" "Cloning Project Files"
  # wait for the copy only, never for other background jobs of the shell
  wait "${copy_pid}"
  copy_status=$(cat "${VDM_SRC_PATH}/.clone_status" 2>/dev/null)
  ##########################
  ### 18. start the source containers again (even when the copy failed)
  if ${source_running}; then
    echo "Starting the (${container}) containers again, please wait..."
    if ! composeSourceContainer "${container}" 'start'; then
      restart_status=1
      # shown right away, so it is never lost when the clone is rolled back below
      showError "The (${container}) containers could not be started again after the copy.\n\n\
Use (Enable existing container) or (Pull up all enabled containers) to start (${container}) again." 12
      warnings+="  - The (${container}) containers could not be started again, start them from the menu.\n"
    fi
  fi
  if [ "${copy_status}" != "0" ]; then
    showError "The project folder could not be copied, so the clone was rolled back:\n\n$(cat "${VDM_SRC_PATH}/.clone_error" 2>/dev/null)" 16
    rm -f "${VDM_SRC_PATH}/.clone_status" "${VDM_SRC_PATH}/.clone_error"
    cloneJoomlaRollback "${new_dir}" "${new_project}" "${project_created}" "${shared_env}" "${env_added}"
    return 1
  fi
  rm -f "${VDM_SRC_PATH}/.clone_status" "${VDM_SRC_PATH}/.clone_error"
  ##########################
  ### 19. point the cloned configuration.php at the clone's own database (and mailcatcher)
  if ${patch_host}; then
    if ! cloneJoomlaConfiguration "${new_project}/joomla/configuration.php" "${old_key}" "${VDM_KEY}" "${site_name}"; then
      showError "The configuration.php of the clone could not be updated, so the clone was rolled back."
      cloneJoomlaRollback "${new_dir}" "${new_project}" "${project_created}" "${shared_env}" "${env_added}"
      return 1
    fi
  fi
  ##########################
  ### 20. set host file if needed
  updateHostFile
  # also set the database domain
  updateHostFile "${VDM_SUBDOMAIN}db"
  # and the mailcatcher domain
  ${VDM_SRC_MAILCATCHER} && updateHostFile "${VDM_SUBDOMAIN}mail"
  ##########################
  ### 21. things we do not change, but the user should know about
  if ! ${patch_host}; then
    warnings+="  - The database host (${host}) was NOT changed, the clone shares that database.\n"
  fi
  if [ -n "$(getJoomlaConfigValue "${new_project}/joomla/configuration.php" 'live_site')" ]; then
    warnings+="  - configuration.php sets \$live_site, check that it fits ${new_container}.\n"
  fi
  if [ -n "$(getJoomlaConfigValue "${new_project}/joomla/configuration.php" 'cookie_domain')" ]; then
    warnings+="  - configuration.php sets \$cookie_domain, check that it fits ${new_container}.\n"
  fi
  if runPrivileged grep -qs "${container}" "${new_project}/joomla/.htaccess" "${new_project}/joomla/robots.txt" "${new_project}/joomla/web.config"; then
    warnings+="  - ${container} is mentioned in .htaccess, robots.txt or web.config of the clone, check them.\n"
  fi
  ##########################
  ### 22. show the details of the clone
  message="                                                                      ${PROGRAM_NAME} v$_VERSION

  The (${container}) container was cloned to (${new_container}).
  --------------------------------------------------------------------
    URL:              ${scheme}${new_container}
    PHPMYADMIN:       ${scheme}${VDM_SUBDOMAIN}db.${VDM_DOMAIN}
    DATABASE_HOST:    mariadb${VDM_KEY}:3306
  --------------------------------------------------------------------
    DOCKER COMPOSE:   ${new_yml}
    PROJECT FOLDER:   ${new_project}
    ENV VALUES:       VDM_${new_env}_* in ${env_target}
  --------------------------------------------------------------------
  The database name, users, passwords and table prefix are the same as in (${container}).
  The clone is NOT enabled yet, use (Enable existing container) to start it.
"
  [ -n "${warnings}" ] && message+="
  Please check:
${warnings}"
  whiptail --msgbox "${message}" --fb --scrolltext --title "Clone Complete" --backtitle "${BACK_TITLE}" "$(getDialogHeight "${message}" 9)" 112
  # return a success
  return "${restart_status}"
}

# stop or start the containers of an enabled Joomla container
# $1: container name (sub.domain.tld)   $2: stop or start
function composeSourceContainer() {
  local container="${1:-}"
  local action="${2:-stop}"
  local yml="${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/enabled/${container}/docker-compose.yml"
  local evn_file
  [ -f "${yml}" ] || return 1
  # check if image has its own env file also
  evn_file=$(getContainerEnvFile "${VDM_CONTAINER_TYPE}" "${container}")
  if [ ${#evn_file} -ge 1 ]; then
    docker compose --env-file "${evn_file}" --file "${yml}" "${action}"
  else
    docker compose --file "${yml}" "${action}"
  fi
}

# remove what a failed clone created, so the host is left as it was
# $1: new compose directory   $2: new project folder   $3: true when the project folder was created
# $4: shared env file         $5: the env variable names added to it (one per line, as printed
#                                 by cloneContainerEnvVariables)
function cloneJoomlaRollback() {
  local new_dir="${1:-}"
  local new_project="${2:-}"
  local project_created="${3:-false}"
  local shared_env="${4:-}"
  local env_added="${5:-}"
  local -a env_names=()
  # the compose directory (and a per-container .env in it)
  if [ -n "${new_dir}" ] && [ -d "${new_dir}" ]; then
    rm -rf "${new_dir}"
  fi
  # the copied project folder (only the one we created, and only inside the projects path)
  if [ "${project_created}" = "true" ] && [ -n "${new_project}" ] && [ -d "${new_project}" ] &&
    [[ "${new_project}" == "${VDM_PROJECT_PATH}/"?* ]]; then
    runPrivileged rm -rf "${new_project}"
  fi
  # only the env values this clone added to the shared env file
  if [ -n "${env_added}" ]; then
    mapfile -t env_names <<<"${env_added}"
    removeContainerEnvVariables "${shared_env}" "${env_names[@]}" ||
      showError "The VDM_* values added by the clone could not be removed from ${shared_env}.\n\nRemove these lines by hand:\n${env_added}" 16
  fi
}

#####################################################################################################################VDM
######################################## DELETE JOOMLA
function joomla__TRuST__delete() {
  # check if this type has enabled containers
  if ! hasDirectories "${VDM_CONTAINER_TYPE}/available/"; then
    showError "There are no ${VDM_CONTAINER_TYPE^} containers available."
  else
    # set some local variables
    local vdm_delete_me
    local container
    local evn_file
    # saved the file
    showNotice "Only delete containers of which you have made absolutely sure it's no longer needed! Better to just disable them if all you want is to just take them down."
    # get containers to enable
    vdm_delete_me=$(getSelectedDirectories "Select container/s to delete." \
      "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/available/" "Delete ${VDM_CONTAINER_TYPE^} Container/s")
    # check that we have something, else return to main menu
    if [ ${#vdm_delete_me} -ge 1 ]; then
      # convert the string to and array
      IFS=' ' read -r -a vdm_delete_me_array <<<"${vdm_delete_me[@]}"
      # loop over the directories to build the
      for containered in "${vdm_delete_me_array[@]}"; do
        # remove the " from the string
        container="${containered//\"/}"
        # check if the container is still enabled
        if [ -d "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/enabled/${container}" ]; then
          # check if image has its own env file also
          evn_file=$(getContainerEnvFile "${VDM_CONTAINER_TYPE}" "${container}")
          # make sure the docker image is stopped
          runContainerCompose "${evn_file}" "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/enabled/${container}/docker-compose.yml" down || return $?
          # then remove soft link
          rm -rf "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/enabled/${container}" || return $?
        fi
        # before deleting the config we ask to make sure
        if getInputYesNo "Would you like to delete the (${container}) container's folder that holds the docker-compose.yml file?" \
            "Delete Docker Compose Yaml" 8 112; then
          # then remove docker-compose.yml file
          rm -rf "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/available/${container}" || return $?
        fi
      done
    fi
    # ask if there are volumes to delete
    if hasDirectories '' "${VDM_PROJECT_PATH}" && \
      getInputYesNo "Would you like to delete persistent volumes found in (${VDM_PROJECT_PATH})?" \
      "Continue To Delete Persistent Volumes" 12 112; then
      # trigger the volumes removal script
      deletePersistentVolumes
    fi
  fi
}

#####################################################################################################################VDM
######################################## DELETE OPENSSH
function openssh__TRuST__delete() {
  # check if this type has enabled containers
  if ! hasDirectories "${VDM_CONTAINER_TYPE}/available/"; then
    showError "There are no ${VDM_CONTAINER_TYPE^} containers available."
  else
    # set some local variables
    local vdm_delete_me
    local container
    # saved the file
    showNotice "Only delete containers of which you have made absolutely sure it's no longer needed! Better to just disable them if all you want is to just take them down."
    # get containers to enable
    vdm_delete_me=$(getSelectedDirectories "Select container/s to delete." \
      "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/available/" "Delete ${VDM_CONTAINER_TYPE^} Container/s")
    # check that we have something, else return to main menu
    if [ ${#vdm_delete_me} -ge 1 ]; then
      # convert the string to and array
      IFS=' ' read -r -a vdm_delete_me_array <<<"${vdm_delete_me[@]}"
      # loop over the directories to build the
      for containered in "${vdm_delete_me_array[@]}"; do
        # remove the " from the string
        container="${containered//\"/}"
        # check if the container is still enabled
        if [ -d "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/enabled/${container}" ]; then
          # make sure the docker image is stopped
          local evn_file
          evn_file=$(getContainerEnvFile "${VDM_CONTAINER_TYPE}" "${container}")
          runContainerCompose "${evn_file}" "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/enabled/${container}/docker-compose.yml" down || return $?
          # then remove soft link
          rm -fr "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/enabled/${container}" || return $?
        fi
        # before deleting the config we ask to make sure
        if getInputYesNo "Would you like to delete the (${container}) container's folder that holds the docker-compose.yml file?" \
            "Delete Docker Compose Yaml" 8 112; then
          # then remove docker-compose.yml file
          rm -fr "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/available/${container}" || return $?
        fi
      done
    fi
  fi
}

#####################################################################################################################VDM
######################################## DELETE TRAEFIK
function traefik__TRuST__delete() {
  # check if traefik has been setup
  if [ ! -f "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/docker-compose.yml" ]; then
    showError "There is no ${VDM_CONTAINER_TYPE^} container to delete."
  else
    # make sure the docker image is stopped
    local evn_file=''
    if [ -f "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/.env" ]; then
      evn_file="${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/.env"
    elif [ -f "${VDM_SRC_PATH}/.env" ]; then
      evn_file="${VDM_SRC_PATH}/.env"
    fi
    runContainerCompose "${evn_file}" "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/docker-compose.yml" down || return $?
    # before deleting the config we ask to make sure
    if getInputYesNo "Would you like to delete the ${VDM_CONTAINER_TYPE^} container's docker-compose.yml file?" \
      "Delete Docker Compose Yaml" 8 112; then
      # then remove docker-compose.yml file
      rm -fr "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/docker-compose.yml"
    fi
  fi
}

#####################################################################################################################VDM
######################################## DELETE PORTAINER
function portainer__TRuST__delete() {
  # check if portainer has been setup
  if [ ! -f "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/docker-compose.yml" ]; then
    showError "There is no ${VDM_CONTAINER_TYPE^} container to delete."
  else
    # make sure the docker image is stopped
    local evn_file=''
    if [ -f "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/.env" ]; then
      evn_file="${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/.env"
    elif [ -f "${VDM_SRC_PATH}/.env" ]; then
      evn_file="${VDM_SRC_PATH}/.env"
    fi
    runContainerCompose "${evn_file}" "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/docker-compose.yml" down || return $?
    # before deleting the config we ask to make sure
    if getInputYesNo "Would you like to delete the ${VDM_CONTAINER_TYPE^} container's docker-compose.yml file?" \
      "Delete Docker Compose Yaml" 8 112; then
      # then remove docker-compose.yml file
      rm -fr "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/docker-compose.yml"
    fi
  fi
}

#####################################################################################################################VDM
######################################## RESET JOOMLA
function joomla__TRuST__reset() {
  # ask if there are volumes to delete
  if hasDirectories '' "${VDM_PROJECT_PATH}" && \
    getInputYesNo "Would you like to reset persistent volumes found in (${VDM_PROJECT_PATH})?" \
    "Continue To Reset Persistent Volumes" 12 112; then
    # trigger the volumes reset script
    resetPersistentJoomlaVolumes
  fi
}

#####################################################################################################################VDM
######################################## Migrate Joomla
function joomla__TRuST__migratefiles() {
  # check if this type have available containers
  if ! hasDirectories "${VDM_CONTAINER_TYPE}/available/"; then
    showError "The path ${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/available/ does not exist or is empty, first run a ${VDM_CONTAINER_TYPE^} setup."
  else
    # set some local variables
    local type_migration
    local vdm_migrate_me
    local container
    # list containers... and allow selection to edit
    container=$(getSelectedDirectory "Select the container you would like to migrate.\n[Only continue if you know what your doing!] (We will only move docker-composer.yml file)" \
      "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/available/" '' "Migrate ${VDM_CONTAINER_TYPE^} Container")
    # check that we have something, else return to main menu
    if [ ${#container} -ge 1 ]; then
      # add the parent dir back
      vdm_migrate_me="${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/available/${container}/docker-compose.yml"
      # check if this docker-composer.yml exist
      if [ -f "${vdm_migrate_me}" ]; then
        # select the type of migration
        type_migration=$(getMigrationType)
        # get remote system
        remote_system=$(getRemoteSystem)
        # make sure we have a remote
        if [ ${#remote_system} -ge 2 ] && [ "${remote_system}" != "none_selected" ]; then
          # give little heads-up
          if (whiptail --yesno "${USER^}, you selected the container:<${container}> action:<${type_migration}> remote:<${remote_system}>\nIs this correct, and can we continue with the migration ${type_migration}?" \
            --title "Confirm Migration ${type_migration^}" --backtitle "${BACK_TITLE}" 8 112); then
            # run migration
            "${type_migration}ContainerMigration" "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/available/${container}" "${VDM_CONTAINER_TYPE}/available/${container}" "${remote_system}"
          fi
        else
          showError "Migration cancelled since no remote system was selected."
        fi
      fi
    fi
  fi
}

#####################################################################################################################VDM
######################################## Migrate OPENSSH
function openssh__TRuST__migrate() {
  # check if this type have available containers
  if ! hasDirectories "${VDM_CONTAINER_TYPE}/available/"; then
    showError "The path ${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/available/ does not exist or is empty, first run a ${VDM_CONTAINER_TYPE^} setup."
  else
    # set some local variables
    local vdm_migrate_me
    local container
    # list containers... and allow selection to edit
    container=$(getSelectedDirectory "Select the container you would like to migrate.\n[Only continue if you know what your doing!] (We will only move docker-composer.yml file)" \
      "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/available/" '' "Migrate ${VDM_CONTAINER_TYPE^} Container")
    # check that we have something, else return to main menu
    if [ ${#container} -ge 1 ]; then
      # add the parent dir back
      vdm_migrate_me="${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/available/${container}/docker-compose.yml"
      # check if this docker-composer.yml exist
      if [ -f "${vdm_migrate_me}" ]; then
        # select the type of migration
        type_migration=$(getMigrationType)
        # get remote system
        remote_system=$(getRemoteSystem)
        # make sure we have a remote
        if [ ${#remote_system} -ge 2 ] && [ "${remote_system}" != "none_selected" ]; then
          # give little heads-up
          if (whiptail --yesno "${USER^}, you selected the container:<${container}> action:<${type_migration}> remote:<${remote_system}>\nIs this correct, and can we continue with the migration ${type_migration}?" \
            --title "Confirm Migration ${type_migration^}" --backtitle "${BACK_TITLE}" 8 112); then
            # run migration
            "${type_migration}ContainerMigration" "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/available/${container}" "${VDM_CONTAINER_TYPE}/available/${container}" "${remote_system}"
          fi
        else
          showError "Migration cancelled since no remote system was selected."
        fi
      fi
    fi
  fi
}

#####################################################################################################################VDM
######################################## Migrate Directory
function directory__TRuST__migrate() {
  # set some local variables
  local vdm_migrate_me
  local directory
  # Would you also like to move a project folder
  if hasDirectories '' "${VDM_PROJECT_PATH}"; then
    # get project directories to migrate
    directory=$(getSelectedDirectory "Select project directory to migrate.\n[Only continue if you know what your doing!]" \
    "${VDM_PROJECT_PATH}" "Select Project Directory")
    # check that we have something, else return to main menu
    if [ ${#directory} -ge 1 ]; then
      # add the parent dir back
      vdm_migrate_me="${VDM_PROJECT_PATH}/${directory}"
      # check that we have something
      if [ -d "${vdm_migrate_me}" ]; then
        # select the type of migration
        type_migration=$(getMigrationType)
        # get remote system
        remote_system=$(getRemoteSystem)
        # make sure we have a remote
        if [ ${#remote_system} -ge 2 ] && [ "${remote_system}" != "none_selected" ]; then
          # give little heads-up
          if (whiptail --yesno "${USER^}, you selected the directory:<${directory}> action:<${type_migration}> remote:<${remote_system}>\nIs this correct, and can we continue with the migration ${type_migration}?" \
            --title "Confirm Migration ${type_migration^}" --backtitle "${BACK_TITLE}" 8 112); then
            # run migration
            "${type_migration}DirectoryMigration" "${vdm_migrate_me}" "${directory}" "${remote_system}"
          fi
        else
          showError "Migration cancelled since no remote system was selected."
        fi
      fi
    fi
  fi
}

#####################################################################################################################VDM
######################################## MENU ACTIONS

# setup a container
function setupContainer() {
  # make sure the networks are set
  setNetworks || return $?
  # make sure of our container type
  VDM_CONTAINER_TYPE="${1}"
  VDM_TASK="setup"
  # execute the task
  main
}

# setup multiple containers
function bulkSetupContainers() {
  # make sure the networks are set
  setNetworks || return $?
  # make sure of our container type
  VDM_CONTAINER_TYPE="${1}"
  VDM_TASK="bulk"
  # execute the task
  main
}

# edit a container
function editContainer() {
  # make sure of our container type
  VDM_CONTAINER_TYPE="${1}"
  VDM_TASK="edit"
  # execute the task
  main
}

# enable a container
function enableContainer() {
  # make sure of our container type
  VDM_CONTAINER_TYPE="${1}"
  VDM_TASK="enable"
  # execute the task
  main
}

# disable a container
function disableContainer() {
  # make sure of our container type
  VDM_CONTAINER_TYPE="${1}"
  VDM_TASK="disable"
  # execute the task
  main
}

# down containers
function downContainers() {
  # make sure of our container type
  VDM_CONTAINER_TYPE="${1}"
  VDM_TASK="down"
  # execute the task
  main
}

# up containers
function upContainers() {
  # make sure of our container type
  VDM_CONTAINER_TYPE="${1}"
  VDM_TASK="up"
  # execute the task
  main
}

# clone a container
function cloneContainer() {
  # make sure of our container type
  VDM_CONTAINER_TYPE="${1}"
  VDM_TASK="clone"
  # execute the task
  main
}

# clone the project files (persistent volume) of a container
function cloneProjectFiles() {
  # make sure of our container type
  VDM_CONTAINER_TYPE="${1}"
  VDM_TASK="clonefiles"
  # execute the task
  main
}

# delete a container
function deleteContainer() {
  # make sure of our container type
  VDM_CONTAINER_TYPE="${1}"
  VDM_TASK="delete"
  # execute the task
  main
}

# reset a container
function resetContainer() {
  # make sure of our container type
  VDM_CONTAINER_TYPE="${1}"
  VDM_TASK="reset"
  # execute the task
  main
}

# migrate a container
function migrateContainer() {
  # make sure of our container type
  VDM_CONTAINER_TYPE="${1}"
  VDM_TASK="migrate"
  # execute the task
  main
}

# Run a permission operation in the background for the gauge, then wait for
# that specific job and preserve its result before another operation starts.
function runPermissionProgress() {
  local message="${1:-}"
  local permission_pid permission_status=0
  shift
  progressSwitchOn || return 1
  {
    "$@" || permission_status=$?
    progressSwitchOff
    exit "${permission_status}"
  } &
  permission_pid=$!
  showProgress "${message}"
  wait "${permission_pid}" || permission_status=$?
  if [ "${permission_status}" -ne 0 ]; then
    showError "The permission update failed (exit status ${permission_status}).\n\nReview the command output and correct the failure before continuing."
  fi
  return "${permission_status}"
}

function fixJoomlaFilePermissions() {
  local project="${1}" file
  sudo find "${project}" -type f -exec chmod 644 {} + || return $?
  for file in configuration.php .htaccess php.ini; do
    [ -f "${project}/${file}" ] || continue
    if [ "${file}" = 'configuration.php' ]; then
      sudo chmod 444 "${project}/${file}" || return $?
    else
      sudo chmod 400 "${project}/${file}" || return $?
    fi
  done
}

function fixJoomlaDirectoryPermissions() {
  local project="${1}" folder rules
  sudo find "${project}" -type d -exec chmod 755 {} + || return $?
  rules=$(lockFolder) || return $?
  for folder in .idea .hidden .git; do
    [ -d "${project}/${folder}" ] || continue
    sudo chmod -R 700 "${project}/${folder}" || return $?
    sudo tee "${project}/${folder}/.htaccess" <<<"${rules}" >/dev/null || return $?
    sudo chmod 400 "${project}/${folder}/.htaccess" || return $?
  done
  if [ -d "${project}/tmp" ]; then
    sudo chmod -R 700 "${project}/tmp" || return $?
  fi
}

# To fix the permissions of Joomla containers
function fixContainersPermissions() {
  if [ ! -d "${VDM_PROJECT_PATH}" ]; then
    showError "The ${VDM_PROJECT_PATH} does not exist."
    return 1
  elif ! hasDirectories '' "${VDM_PROJECT_PATH}"; then
    showError "There are no persistent volumes in ${VDM_PROJECT_PATH} available."
    return 1
  fi
  local vdm_fix_me persistent volume project user_id
  local -a vdm_fix_me_array=()
  vdm_fix_me=$(getSelectedDirectories "Select persistent volume to fix." \
    "${VDM_PROJECT_PATH}" "Fix Joomla Permissions") || return $?
  [ -n "${vdm_fix_me}" ] || return 0
  if ! whiptail --yesno "${USER^}, to fix these permissions we need sudo privileges." \
    --title "Give sudo Privileges" --backtitle "${BACK_TITLE}" 8 112; then
    return 0
  fi
  sudo -v || return $?
  IFS=' ' read -r -a vdm_fix_me_array <<<"${vdm_fix_me}"
  for volume in "${vdm_fix_me_array[@]}"; do
    persistent="${volume//\"/}"
    project="${VDM_PROJECT_PATH}/${persistent}"
    if [ ! -d "${project}/joomla" ]; then
      showError "${project} is not a Joomla persistent volume and was skipped."
      return 1
    fi
    showNotice "Fixing ${persistent}/joomla permissions now."
    setContainerUser "$(id -u)" || return $?
    runPermissionProgress "Setting the ownership of ${persistent} Joomla directory/files." \
      sudo chown -R "${VDM_PUID}:${VDM_PGID}" "${project}/joomla" || return $?
    runPermissionProgress "Setting the file permissions for ${persistent} Joomla." \
      fixJoomlaFilePermissions "${project}/joomla" || return $?
    runPermissionProgress "Setting the directory permissions for ${persistent} Joomla." \
      fixJoomlaDirectoryPermissions "${project}/joomla" || return $?
    user_id=$(id -u)
    if [ "${user_id}" != "${VDM_PUID}" ]; then
      if ! command -v setfacl >/dev/null 2>&1; then
        showError "Install setfacl to allow user:${USER} to access the Joomla files, then run this fix again."
        return 1
      fi
      runPermissionProgress "Setting permissions so user:${USER} can access and edit ${persistent} Joomla." \
        sudo setfacl -R -m "u:${USER}:rwx" "${project}/joomla" || return $?
    elif command -v setfacl >/dev/null 2>&1; then
      sudo setfacl -R -b "${project}/joomla" || return $?
    fi
    if [ -d "${project}/db" ]; then
      runPermissionProgress "Setting the ownership of ${persistent} database directory/files." \
        sudo chown -R 999:999 "${project}/db" || return $?
      runPermissionProgress "Setting the file permissions for ${persistent} database." \
        sudo find "${project}/db" -type f -exec chmod 660 {} + || return $?
      runPermissionProgress "Setting the directory permissions for ${persistent} database." \
        sudo find "${project}/db" -type d -exec chmod 700 {} + || return $?
    fi
    showNotice "Permissions update completed!"
  done
}

# Project operations may only target a direct directory inside the projects path.
function isSafeProjectName() {
  [[ "${1:-}" =~ ^[A-Za-z0-9][A-Za-z0-9_.-]*$ ]]
}

# Refuse destructive operations when Docker cannot confirm a project is stopped.
# A manually renamed bind directory can differ from its container key.
function ensureProjectStopped() {
  local persistent="${1:-}" running_names yml key
  local -a keys=("${persistent}")
  if ! isSafeProjectName "${persistent}" || [ -L "${VDM_PROJECT_PATH}/${persistent}" ]; then
    showError "The project name (${persistent}) must identify a direct project directory."
    return 1
  fi
  running_names=$(docker ps --format '{{.Names}}') || {
    showError "Docker could not inspect running containers. The (${persistent}) project was left unchanged."
    return 1
  }
  for yml in "${VDM_REPO_PATH}/joomla/available/"*/docker-compose.yml; do
    [ -f "${yml}" ] || continue
    if key=$(getJoomlaComposeIdentity "${yml}" &&
      [ "${VDM_SRC_PROJECT_FOLDER}" = "${persistent}" ] && printf '%s' "${VDM_SRC_KEY}"); then
      keys+=("${key}")
    fi
  done
  for key in "${keys[@]}"; do
    if printf '%s\n' "${running_names}" | grep -qxF -e "mariadb${key}" -e "joomla${key}" -e "phpmyadmin${key}"; then
      showError "The (${persistent}) project is in use by running containers. Disable them before deleting or resetting its files."
      return 1
    fi
  done
}

# delete persistent volumes
function deletePersistentVolumes() {
  # we first check if we have some volumes
  if hasDirectories '' "${VDM_PROJECT_PATH}"; then
    # set some local variables
    local vdm_delete_volumes
    local persistent
    # saved the file
    showNotice "Only delete persistent volumes of which you have made absolutely sure it's no longer in use!"
    # get containers to enable
    vdm_delete_volumes=$(getSelectedDirectories "Select persistent volume\s to delete." \
      "${VDM_PROJECT_PATH}" "Select Persistent Volume\s to Delete")
    # check that we have something, else return to main menu
    if [ ${#vdm_delete_volumes} -ge 1 ]; then
      # convert the string to and array
      IFS=' ' read -r -a vdm_delete_volumes_array <<<"${vdm_delete_volumes[@]}"
      # loop over the directories to build the
      for volumes in "${vdm_delete_volumes_array[@]}"; do
        # remove the " from the string
        persistent="${volumes//\"/}"
        ensureProjectStopped "${persistent}" || return $?
        # last serious check and then its gone
        if [ -d "${VDM_PROJECT_PATH}/${persistent}" ] &&
          (whiptail --yesno "Are you absolutely sure you would like to delete this (${persistent}) persistent volume? THIS CAN'T BE UNDONE!\n(we need sudo privileges)" \
            --title "Delete Persistent Volume" --backtitle "${BACK_TITLE}" 15 112); then
          # then remove soft link
          sudo rm -rf "${VDM_PROJECT_PATH}/${persistent}" || return $?
        fi
      done
    fi
  else
    showError "There are no persistent volumes found in ${VDM_PROJECT_PATH}."
  fi
}

# clone persistent volume
function clonePersistentVolume() {
  # we first check if we have some volumes
  if hasDirectories '' "${VDM_PROJECT_PATH}"; then
    # set some local variables
    local vdm_clone_volume
    local persistent
    local new_persistent
    local database_state=0
    # get containers to enable
    vdm_clone_volume=$(getSelectedDirectory "Select persistent volume\s to clone." \
      "${VDM_PROJECT_PATH}" "Select Persistent Volume to Clone")
    # check that we have something, else return to main menu
    if [ ${#vdm_clone_volume} -ge 1 ]; then
      # remove the " from the string
      persistent="${vdm_clone_volume//\"/}"
      if ! isSafeProjectName "${persistent}" || [ -L "${VDM_PROJECT_PATH}/${persistent}" ]; then
        showError "Select a direct project directory to clone."
        return 1
      fi
      # last serious check and then its gone
      if [ -d "${VDM_PROJECT_PATH}/${persistent}" ]; then
        # warn when the database of this project is still running (a live copy can be inconsistent)
        isContainerRunning "mariadb${persistent}" || database_state=$?
        if [ "${database_state}" -gt 1 ]; then
          showError "Docker could not inspect the database. The project folder was not copied."
          return 1
        fi
        if [ "${database_state}" -eq 0 ] && ! getInputYesNo "The database container (mariadb${persistent}) is running.\n\
Copying a running database can produce an inconsistent copy. Disable the container first, or continue at your own risk.\n\n\
Would you like to continue anyway?" "Database Is Running" 12 112 "defaultno"; then
          showNotice "The (${persistent}) project folder was not copied, because its database container is running." 8
          return 0
        fi
        # set the new persistent volume name
        new_persistent="${persistent}"
        while ! isSafeProjectName "${new_persistent}" || [ -e "${VDM_PROJECT_PATH}/${new_persistent}" ] ||
          [ -L "${VDM_PROJECT_PATH}/${new_persistent}" ]; do
          # get the value
          new_persistent=$(getInput "Enter a new persistent volume name\n[Use letters, numbers, dots, underscores or hyphens; do not use an existing name]" '' 'Enter Persistent Name') || return $?
          # keep asking
          if ! isSafeProjectName "${new_persistent}"; then
            showError "Enter a direct project folder name using letters, numbers, dots, underscores or hyphens."
          elif [ -e "${VDM_PROJECT_PATH}/${new_persistent}" ] || [ -L "${VDM_PROJECT_PATH}/${new_persistent}" ]; then
            showError "You must enter a persistent volume name that does not already exist.\n\n${new_persistent} already exist."
          fi
        done
        # create this new folder
        mkdir "${VDM_PROJECT_PATH}/${new_persistent}" || return $?
        # clone or (copy) the files to a new directory (including hidden files).
        local copy_status=0
        sudo cp -a "${VDM_PROJECT_PATH}/${persistent}/." "${VDM_PROJECT_PATH}/${new_persistent}/" || copy_status=$?
        if [ "${copy_status}" -ne 0 ]; then
          sudo rm -rf "${VDM_PROJECT_PATH}/${new_persistent}" ||
            showError "The incomplete copy (${new_persistent}) could not be removed."
          showError "The (${persistent}) project could not be copied (exit status ${copy_status})."
          return "${copy_status}"
        fi
      fi
    fi
  else
    showError "There are no persistent volumes found in ${VDM_PROJECT_PATH}."
  fi
}

#####################################################################################################################VDM
######################################## CLONE HELPERS (no user interaction, so they can be tested)

# the env variable name suffixes a Joomla container reads through its env key (VDM_<ENV_KEY>_<suffix>)
# returned as an extended regular expression alternation
function getJoomlaEnvSuffixes() {
  echo 'DB|DB_USER|DB_PASS|DB_ROOT|PUID|PGID|JOOMLA_[A-Z_]+|EXTENSIONS_URLS|CLI_COMMANDS'
}

# read the identity of a Joomla container from its docker-compose.yml
# $1: path to the docker-compose.yml
# sets: VDM_SRC_KEY, VDM_SRC_ENV_KEY, VDM_SRC_PROJECT_FOLDER, VDM_SRC_MAILCATCHER,
#       VDM_SRC_NAMED_VOLUMES, VDM_SRC_SECURE
# returns 1 when the key or env key could not be found (hand written file)
function getJoomlaComposeIdentity() {
  local yml="${1:-}"
  VDM_SRC_KEY=''
  VDM_SRC_ENV_KEY=''
  VDM_SRC_PROJECT_FOLDER=''
  VDM_SRC_MAILCATCHER=false
  VDM_SRC_NAMED_VOLUMES=false
  VDM_SRC_SECURE=false
  [ -f "${yml}" ] || return 1
  # the key is the suffix of the database container name
  VDM_SRC_KEY=$(sed -nE 's/^[[:space:]]*container_name:[[:space:]]*mariadb([A-Za-z]+)[[:space:]]*$/\1/p' "${yml}" | head -n 1)
  # the env key is the middle part of the database name variable (comment lines are ignored)
  VDM_SRC_ENV_KEY=$(sed -nE '/^[[:space:]]*#/!s/^.*MARIADB_DATABASE=[$][{]VDM_([A-Za-z]+)_DB[}].*$/\1/p' "${yml}" | head -n 1)
  if [ ${#VDM_SRC_KEY} -lt 1 ] || [ ${#VDM_SRC_ENV_KEY} -lt 1 ]; then
    return 1
  fi
  # optional features
  grep -qE "^[[:space:]]*container_name:[[:space:]]*mailcatcher${VDM_SRC_KEY}[[:space:]]*$" "${yml}" && VDM_SRC_MAILCATCHER=true
  grep -qE "^[[:space:]]*-[[:space:]]*${VDM_SRC_KEY,,}_(web|db):/var/" "${yml}" && VDM_SRC_NAMED_VOLUMES=true
  grep -qE 'entrypoints=websecure|tls\.certresolver=' "${yml}" && VDM_SRC_SECURE=true
  # the project folder (persistent volume) named in the active bind mounts (comment lines are ignored)
  VDM_SRC_PROJECT_FOLDER=$(sed -nE '/^[[:space:]]*#/!s#^.*PROJECT_PATH[}]/([^/]+)/db:/var/lib/mysql.*$#\1#p' "${yml}" | head -n 1)
  [ -n "${VDM_SRC_PROJECT_FOLDER}" ] ||
    VDM_SRC_PROJECT_FOLDER=$(sed -nE '/^[[:space:]]*#/!s#^.*PROJECT_PATH[}]/([^/]+)/joomla:/var/www/html.*$#\1#p' "${yml}" | head -n 1)
  export VDM_SRC_KEY
  export VDM_SRC_ENV_KEY
  export VDM_SRC_PROJECT_FOLDER
  export VDM_SRC_MAILCATCHER
  export VDM_SRC_NAMED_VOLUMES
  export VDM_SRC_SECURE
  return 0
}

# escape a string for use inside an extended regular expression (also escapes the # delimiter)
function getEscapedRegex() {
  # shellcheck disable=SC2016
  printf '%s' "${1:-}" | sed -e 's/[][\.*^$(){}?+|#/]/\\&/g'
}

# write a copy of a Joomla docker-compose.yml with a new identity
# $1: source docker-compose.yml   $2: target docker-compose.yml
# $3: old key                     $4: new key
# $5: old env key                 $6: new env key
# $7: old sub-domain              $8: new sub-domain
# $9: old domain                  $10: new domain
# $11 (optional): the project folder the source mounts, when it is not the old key
# Keys are alphabetical only, so every token can be anchored on a non-letter.
# Lines with a Traefik Host() rule are handled on their own, so a domain that happens
# to contain a service name and the key (joomlasite.com with key site) is never touched.
# returns 1 when the source is missing or sed failed,
#         2 when a value of the source survived, or a host or mount is not the clone's own
function rewriteJoomlaComposeIdentity() {
  local src="${1:-}"
  local dst="${2:-}"
  local old_key="${3:-}"
  local new_key="${4:-}"
  local old_env="${5:-}"
  local new_env="${6:-}"
  local old_sub="${7:-}"
  local new_sub="${8:-}"
  local old_domain="${9:-}"
  local new_domain="${10:-}"
  local src_folder="${11:-$3}"
  local suffixes
  local old_domain_re
  local folder
  local folder_re
  local pattern
  local active
  local mount
  local mount_source
  local mount_target
  local mount_folder
  local mount_volume
  local host
  local -a sed_args=()
  local -a leftovers=()
  [ -f "${src}" ] && [ -n "${dst}" ] || return 1
  # Never truncate the source through the same path, hard link or symlink.
  [ "${src}" != "${dst}" ] && [ ! "${src}" -ef "${dst}" ] || return 1
  [[ "${old_key}" =~ ^[A-Za-z]+$ && "${new_key}" =~ ^[A-Za-z]+$ &&
    "${old_env}" =~ ^[A-Za-z]+$ && "${new_env}" =~ ^[A-Za-z]+$ &&
    "${old_sub}" =~ ^[A-Za-z]+$ && "${new_sub}" =~ ^[A-Za-z]+$ &&
    "${old_domain}" =~ ^[A-Za-z0-9.-]+$ && "${new_domain}" =~ ^[A-Za-z0-9.-]+$ ]] || return 1
  [ -n "${src_folder}" ] || src_folder="${old_key}"
  suffixes=$(getJoomlaEnvSuffixes)
  old_domain_re=$(getEscapedRegex "${old_domain}")
  # lines with a Traefik Host() rule: only the router name and the hosts change
  # shellcheck disable=SC2016
  sed_args+=(-e '/Host\(`/{')
  sed_args+=(-e 's/(routers\.)(mariadb|joomla|phpmyadmin|mailcatcher)'"${old_key}"'\./\1\2'"${new_key}"'./g')
  if [ "${old_sub}.${old_domain}" != "${new_sub}.${new_domain}" ]; then
    # shellcheck disable=SC2016
    sed_args+=(-e 's/Host\(`'"${old_sub}"'(db|mail)?\.'"${old_domain_re}"'`\)/Host(`'"${new_sub}"'\1.'"${new_domain}"'`)/g')
  fi
  sed_args+=(-e 'b' -e '}')
  # service names, container names, database host, SMTP host and Traefik router/service names
  # A migration may retain its key on another host; only renamed identities
  # are leftovers. The destination host and mount checks still apply below.
  if [ "${old_key}" != "${new_key}" ]; then
    sed_args+=(-e 's/(mariadb|joomla|phpmyadmin|mailcatcher)'"${old_key}"'([^A-Za-z]|$)/\1'"${new_key}"'\2/g')
    leftovers+=('(mariadb|joomla|phpmyadmin|mailcatcher)'"${old_key}"'([^A-Za-z]|$)')
  fi
  # bind mounts under the project path (joomla, db, php.ini, entrypoint.sh)
  for folder in "${src_folder}" "${old_key}"; do
    [ "${folder}" != "${new_key}" ] || continue
    folder_re=$(getEscapedRegex "${folder}")
    sed_args+=(-e 's#PROJECT_PATH[}]/'"${folder_re}"'/#PROJECT_PATH}/'"${new_key}"'/#g')
    leftovers+=('PROJECT_PATH[}]/'"${folder_re}"'/')
  done
  # named volumes (expert mode without persistence)
  if [ "${old_key,,}" != "${new_key,,}" ]; then
    sed_args+=(-e 's/(^|[^A-Za-z_])'"${old_key,,}"'_(web|db)([^A-Za-z_]|$)/\1'"${new_key,,}"'_\2\3/g')
    leftovers+=('(^|[^A-Za-z_])'"${old_key,,}"'_(web|db)([^A-Za-z_]|$)')
  fi
  # environment variable references (only the names a Joomla container reads)
  if [ "${old_env}" != "${new_env}" ]; then
    # shellcheck disable=SC2016
    sed_args+=(-e 's/[$][{]VDM_'"${old_env}"'_('"${suffixes}"')[}]/${VDM_'"${new_env}"'_\1}/g')
    leftovers+=('[$][{]VDM_'"${old_env}"'_('"${suffixes}"')[}]')
  fi
  sed -E "${sed_args[@]}" "${src}" > "${dst}" || return 1
  # the checks below look at the active lines only (comments never reach docker compose)
  active=$(sed -E '/^[[:space:]]*#/d' "${dst}")
  # make sure nothing of the old identity survived (host values are checked below)
  for pattern in "${leftovers[@]}"; do
    # shellcheck disable=SC2016
    if printf '%s\n' "${active}" | sed -E 's/Host\(`[^`]*`\)/Host()/g' | grep -qE "${pattern}"; then
      return 2
    fi
  done
  # a host rule must use the single backtick Host() form the rewrite understands
  # (double quotes, several hosts in one Host() or HostRegexp() cannot be renamed safely)
  # shellcheck disable=SC2016
  if printf '%s\n' "${active}" | sed -E 's/Host\(`[^`]*`\)//g' | grep -qE 'Host(Regexp|SNI|SNIRegexp)?\('; then
    return 2
  fi
  # every host must be one of the clone's own hosts (host names are not case sensitive)
  # shellcheck disable=SC2016
  while IFS= read -r host; do
    case "${host,,}" in
    "${new_sub,,}.${new_domain,,}" | "${new_sub,,}db.${new_domain,,}" | "${new_sub,,}mail.${new_domain,,}") ;;
    *) return 2 ;;
    esac
  done < <(printf '%s\n' "${active}" | grep -oE 'Host\(`[^`]*`\)' | sed -E 's/^Host\(`(.*)`\)$/\1/')
  # the long volume syntax is never written by ${PROGRAM_NAME}, and cannot be checked
  if printf '%s\n' "${active}" | grep -qE 'target:[[:space:]]*"?/var/(lib/mysql|www/html)/?"?[[:space:]]*$'; then
    return 2
  fi
  # every database and web root mount must be the clone's own folder (or named volume)
  while IFS= read -r mount; do
    mount=$(printf '%s' "${mount}" | sed -E 's/^[[:space:]]*-[[:space:]]*//; s/^"//; s/"[[:space:]]*$//')
    mount_source="${mount%%:/var/*}"
    mount_target="${mount#"${mount_source}":}"
    case "${mount_target%%:*}" in
    /var/lib/mysql) mount_folder='db' mount_volume="${new_key,,}_db" ;;
    *) mount_folder='joomla' mount_volume="${new_key,,}_web" ;;
    esac
    # shellcheck disable=SC2016
    if [ "${mount_source}" != '${VDM_PROJECT_PATH}/'"${new_key}/${mount_folder}" ] &&
      [ "${mount_source}" != "${mount_volume}" ]; then
      return 2
    fi
  done < <(printf '%s\n' "${active}" | grep -E ':/var/(lib/mysql|www/html)/?(:[a-z,]+)?"?[[:space:]]*$')
  return 0
}

# get a value from a Joomla configuration.php file
# $1: path to configuration.php   $2: setting name (host, db, sitename, ...)
function getJoomlaConfigValue() {
  local file="${1:-}"
  local name="${2:-}"
  [ -f "${file}" ] || return 1
  sed -nE "s/^[[:space:]]*public[[:space:]]+[\$]${name}[[:space:]]*=[[:space:]]*'(.*)';[[:space:]]*\$/\\1/p" "${file}" | head -n 1
}

# point a cloned Joomla configuration.php at the clone's own containers
# $1: path to the cloned configuration.php
# $2: old key   $3: new key
# $4 (optional): new site name ('' keeps the current one)
# The file is written in place so it keeps its owner and mode (normally 0444, owned by the container user).
# returns 1 when the file is missing or could not be written, 2 when the database host is not mariadb<old key>
function cloneJoomlaConfiguration() {
  local file="${1:-}"
  local old_key="${2:-}"
  local new_key="${3:-}"
  local site_name="${4:-}"
  local host
  local tmp_file
  local q="'"
  local -a sed_args=()
  [ -f "${file}" ] || return 1
  [[ "${old_key}" =~ ^[A-Za-z]+$ && "${new_key}" =~ ^[A-Za-z]+$ ]] || return 1
  host=$(getJoomlaConfigValue "${file}" 'host')
  # only a site that uses this container's database can be re-pointed safely
  [[ "${host}" =~ ^mariadb${old_key}(:[0-9]+)?$ ]] || return 2
  # database host (the port, if any, is kept)
  sed_args+=(-e 's/^([[:space:]]*public[[:space:]]+[$]host[[:space:]]*=[[:space:]]*'"${q}"')mariadb'"${old_key}"'((:[0-9]+)?'"${q}"';)/\1mariadb'"${new_key}"'\2/')
  # mailcatcher host (only when it pointed at this container's mailcatcher)
  sed_args+=(-e 's/^([[:space:]]*public[[:space:]]+[$]smtphost[[:space:]]*=[[:space:]]*'"${q}"')mailcatcher'"${old_key}"'('"${q}"';)/\1mailcatcher'"${new_key}"'\2/')
  # site name
  if [ -n "${site_name}" ]; then
    # escape for a PHP single quoted string (\ and '), then escape the result for the sed replacement (\ & |)
    site_name=$(printf '%s' "${site_name}" | sed -e 's/[\\]/\\\\/g' -e "s/'/\\\\'/g" -e 's/[\\]/\\\\/g' -e 's/[&|]/\\&/g')
    sed_args+=(-e 's|^([[:space:]]*public[[:space:]]+[$]sitename[[:space:]]*=[[:space:]]*'"${q}"').*('"${q}"';[[:space:]]*)$|\1'"${site_name}"'\2|')
  fi
  tmp_file=$(mktemp) || return 1
  if ! sed -E "${sed_args[@]}" "${file}" > "${tmp_file}"; then
    rm -f "${tmp_file}"
    return 1
  fi
  # write back into the existing file so owner and mode are kept
  if [ -w "${file}" ]; then
    cat "${tmp_file}" > "${file}" || {
      rm -f "${tmp_file}"
      return 1
    }
  elif useSudo; then
    # tee (run with sudo) is what writes the file, the redirects only feed it
    # shellcheck disable=SC2024
    runPrivileged tee "${file}" < "${tmp_file}" > /dev/null || {
      rm -f "${tmp_file}"
      return 1
    }
  else
    # no sudo here (Windows): lift the owner write bit for the write and put it back
    if ! chmod u+w "${file}" || ! cat "${tmp_file}" > "${file}"; then
      chmod u-w "${file}" 2>/dev/null
      rm -f "${tmp_file}"
      return 1
    fi
    chmod u-w "${file}" || {
      rm -f "${tmp_file}"
      return 1
    }
  fi
  rm -f "${tmp_file}"
  return 0
}

# copy the env values of one Joomla env key to another env key
# $1: env file to read   $2: old env key   $3: new env key
# $4 (optional): env file to write (default: the file read)
# A line is only added when the new key does not already have that value.
# Prints the name of every variable it added (one per line), so a rollback can remove exactly those.
function cloneContainerEnvVariables() {
  local src_file="${1:-}"
  local old_env="${2:-}"
  local new_env="${3:-}"
  local dst_file="${4:-$1}"
  local suffixes
  local line
  local suffix
  local value
  local -a lines=()
  [ -f "${src_file}" ] || return 1
  [[ "${old_env}" =~ ^[A-Za-z]+$ && "${new_env}" =~ ^[A-Za-z]+$ ]] || return 1
  [ -n "${dst_file}" ] || return 1
  [ "${old_env}" = "${new_env}" ] && [ "${src_file}" = "${dst_file}" ] && return 0
  suffixes=$(getJoomlaEnvSuffixes)
  # read everything first, so we never read the lines we append (source and target can be the same file)
  mapfile -t lines < "${src_file}" || return 1
  # the target must end with a new line, else the first value is glued onto its last line
  if [ -s "${dst_file}" ] && [ -n "$(tail -c 1 "${dst_file}")" ]; then
    printf '\n' >> "${dst_file}" || return 1
  fi
  for line in "${lines[@]}"; do
    [[ "${line}" =~ ^VDM_${old_env}_(${suffixes})=(.*)$ ]] || continue
    suffix="${BASH_REMATCH[1]}"
    value="${BASH_REMATCH[2]}"
    if [ -f "${dst_file}" ] && grep -qE "^VDM_${new_env}_${suffix}=" "${dst_file}"; then
      continue
    fi
    printf 'VDM_%s_%s=%s\n' "${new_env}" "${suffix}" "${value}" >> "${dst_file}" || return 1
    echo "VDM_${new_env}_${suffix}"
  done
  return 0
}

# check if an env file already has values for a Joomla env key
# $1: env file   $2: env key
function hasContainerEnvVariables() {
  local env_file="${1:-}"
  local env_key="${2:-}"
  [[ "${env_key}" =~ ^[A-Za-z]+$ ]] || return 1
  [ -f "${env_file}" ] && [ -n "${env_key}" ] &&
    grep -qE "^VDM_${env_key}_($(getJoomlaEnvSuffixes))=" "${env_file}"
}

# copy a per-container env file for a cloned container, renaming the env key
# $1: source .env   $2: target .env   $3: old env key   $4: new env key
function cloneContainerEnvFile() {
  local src_file="${1:-}"
  local dst_file="${2:-}"
  local old_env="${3:-}"
  local new_env="${4:-}"
  local suffixes
  [ -f "${src_file}" ] || return 1
  [ -n "${dst_file}" ] && [ "${src_file}" != "${dst_file}" ] &&
    [ ! "${src_file}" -ef "${dst_file}" ] || return 1
  [[ "${old_env}" =~ ^[A-Za-z]+$ && "${new_env}" =~ ^[A-Za-z]+$ ]] || return 1
  suffixes=$(getJoomlaEnvSuffixes)
  if [ "${old_env}" = "${new_env}" ]; then
    cp "${src_file}" "${dst_file}" || return 1
  else
    sed -E 's/^VDM_'"${old_env}"'_('"${suffixes}"')=/VDM_'"${new_env}"'_\1=/' "${src_file}" > "${dst_file}" || return 1
  fi
  chmod 600 "${dst_file}"
}

# remove env variables by name from an env file (used to roll back a failed clone)
# $1: env file   $2...: the variable names to remove (as printed by cloneContainerEnvVariables)
# Only these exact names are removed; the file is replaced in one step, never truncated first.
function removeContainerEnvVariables() {
  local env_file="${1:-}"
  local name
  local names=''
  local tmp_file
  local rc
  [ -f "${env_file}" ] || return 0
  shift
  for name in "$@"; do
    [[ "${name}" =~ ^[A-Za-z_][A-Za-z0-9_]*$ ]] || continue
    names+="${names:+|}${name}"
  done
  [ -n "${names}" ] || return 0
  tmp_file=$(mktemp "${env_file}.XXXXXX") || return 1
  # grep returns 1 when no line is left, which is still a valid result
  grep -vE "^(${names})=" "${env_file}" > "${tmp_file}"
  rc=$?
  if [ "${rc}" -gt 1 ]; then
    rm -f "${tmp_file}"
    return 1
  fi
  if ! chmod 600 "${tmp_file}" || ! mv -f "${tmp_file}" "${env_file}"; then
    rm -f "${tmp_file}"
    return 1
  fi
  return 0
}

# check if a host name is already routed by Traefik for any container ${PROGRAM_NAME} knows
# $1: host (sub.domain.tld), compared without case like DNS and Traefik do
function isJoomlaHostInUse() {
  local host="${1:-}"
  [ -n "${host}" ] || return 0
  # shellcheck disable=SC2016
  grep -qsiF 'Host(`'"${host}"'`)' "${VDM_REPO_PATH}/"*/available/*/docker-compose.yml "${VDM_REPO_PATH}/"*/docker-compose.yml
}

# check if privileged commands should go through sudo
# Linux and macOS use sudo; on Windows (MSYS/Git Bash) the files belong to the user, and a sudo
# found there is the unrelated Windows sudo.exe, so commands run directly.
function useSudo() {
  [ "${OS_NUMBER:-0}" != "3" ] && command -v sudo >/dev/null 2>&1
}

# run a command with sudo where useSudo says so, else directly
function runPrivileged() {
  if useSudo; then
    sudo "$@"
  else
    "$@"
  fi
}

# get a whiptail height that fits a message (long lines wrap), capped at the terminal height
# $1: message (with \n new lines)   $2 (optional): rows the dialog needs besides the text (default 8)
function getDialogHeight() {
  local message="${1:-}"
  local extra="${2:-8}"
  local lines
  local rows
  local height
  lines=$(printf '%b\n' "${message}" | awk '{ n += (length($0) > 106) ? int((length($0) + 105) / 106) : 1 } END { print n + 0 }')
  height=$((lines + extra))
  rows=$(tput lines 2>/dev/null)
  if [[ "${rows}" =~ ^[0-9]+$ ]] && [ "${rows}" -gt 10 ] && [ "${height}" -gt "${rows}" ]; then
    height="${rows}"
  fi
  echo "${height}"
}

# check if a key is already used by a Joomla project folder, a compose file or a docker container
# $1: key
# returns 0 when in use, 1 when available, 2 when the inventory cannot be inspected safely
function isJoomlaKeyInUse() {
  local key="${1:-}"
  local yml names scan_status inventory_dir
  [[ "${key}" =~ ^[A-Za-z]+$ ]] || return 2
  for inventory_dir in "${VDM_PROJECT_PATH}" "${VDM_REPO_PATH}"; do
    if [ ! -d "${inventory_dir}" ] || [ ! -r "${inventory_dir}" ] || [ ! -x "${inventory_dir}" ]; then
      printf '%s\n' 'Could not inspect the project or repository directory for key collisions.' >&2
      return 2
    fi
  done
  for inventory_dir in "${VDM_REPO_PATH}/joomla" "${VDM_REPO_PATH}/joomla/available"; do
    if { [ -e "${inventory_dir}" ] || [ -L "${inventory_dir}" ]; } &&
      { [ ! -d "${inventory_dir}" ] || [ ! -r "${inventory_dir}" ] || [ ! -x "${inventory_dir}" ]; }; then
      printf '%s\n' 'Could not inspect the Joomla Compose directory for key collisions.' >&2
      return 2
    fi
  done
  if [ -e "${VDM_PROJECT_PATH}/${key}" ] || [ -L "${VDM_PROJECT_PATH}/${key}" ]; then
    return 0
  fi
  for yml in "${VDM_REPO_PATH}/joomla/available/"*/docker-compose.yml; do
    [ -e "${yml}" ] || [ -L "${yml}" ] || continue
    scan_status=0
    grep -qE "^[[:space:]]*container_name:[[:space:]]*(mariadb|joomla|phpmyadmin|mailcatcher)${key}[[:space:]]*$" \
      "${yml}" 2>/dev/null || scan_status=$?
    case "${scan_status}" in
    0) return 0 ;;
    1) ;;
    *)
      printf '%s\n' 'Could not inspect an existing Joomla Compose file for key collisions.' >&2
      return 2
      ;;
    esac
  done
  if ! command -v docker >/dev/null 2>&1 ||
    ! names=$(docker ps -a --format '{{.Names}}' 2>/dev/null); then
    printf '%s\n' 'Could not inspect Docker containers for key collisions.' >&2
    return 2
  fi
  printf '%s\n' "${names}" | grep -qxE "(mariadb|joomla|phpmyadmin|mailcatcher)${key}" && return 0
  return 1
}

# reset persistent Joomla volume
function resetPersistentJoomlaVolumes() {
  # we first check if we have some volumes
  if hasDirectories '' "${VDM_PROJECT_PATH}"; then
    # set some local variables
    local vdm_reset_volumes
    local persistent
    # saved the file
    showNotice "Only reset persistent Joomla volumes of which you have made absolutely sure it's no longer in use!"
    # get containers to enable
    vdm_reset_volumes=$(getSelectedDirectories "Select persistent volume\s to reset." \
      "${VDM_PROJECT_PATH}" "Select Persistent Volume\s to Reset")
    # check that we have something, else return to main menu
    if [ ${#vdm_reset_volumes} -ge 1 ]; then
      # convert the string to and array
      IFS=' ' read -r -a vdm_reset_volumes_array <<<"${vdm_reset_volumes[@]}"
      # loop over the directories to build the
      for volumes in "${vdm_reset_volumes_array[@]}"; do
        # remove the " from the string
        persistent="${volumes//\"/}"
        ensureProjectStopped "${persistent}" || return $?
        # last serious check and then its gone
        if [ -d "${VDM_PROJECT_PATH}/${persistent}/joomla" ] &&
          (whiptail --yesno "Are you absolutely sure you would like to delete this (${persistent}/joomla) persistent volume? THIS CAN'T BE UNDONE!\n(we need sudo privileges)" \
            --title "Delete Persistent Volume" --backtitle "${BACK_TITLE}" 15 112); then
          # then remove soft link
          sudo rm -rf "${VDM_PROJECT_PATH}/${persistent}/joomla" || return $?
        fi
        # last serious check and then its gone
        if [ -d "${VDM_PROJECT_PATH}/${persistent}/db" ] &&
          (whiptail --yesno "Are you absolutely sure you would like to delete this (${persistent}/db) persistent volume? THIS CAN'T BE UNDONE!\n(we need sudo privileges)" \
            --title "Delete Persistent Volume" --backtitle "${BACK_TITLE}" 15 112); then
          # then remove soft link
          sudo rm -rf "${VDM_PROJECT_PATH}/${persistent}/db" || return $?
        fi
      done
    fi
  else
    showError "There are no persistent volumes found in ${VDM_PROJECT_PATH}."
  fi
}

# make an update
function runUpdate() {
  if [[ $0 -ef /usr/bin/octojoom ]] && dpkg-query -S /usr/bin/octojoom >/dev/null 2>&1; then
    printf '%s\n' 'This installation is managed by APT. Use apt to upgrade or remove octojoom.' >&2
    return 1
  fi
  # we need sudo permissions
  if getInputYesNo "${USER^}, to update ${PROGRAM_NAME} we need sudo privileges." \
      "Give sudo Privileges" 8 112; then
    local branch download staged
    # get the target branch to use in our update
    if isExpert; then
      branch=$(getTargetBranch) || return 1
    fi
    download=$(mktemp "${TMPDIR:-/tmp}/octojoom-update.XXXXXX") || return 1
    # Keep the installed executable in place until the complete script is valid.
    if ! curl --fail --silent --show-error -L "https://raw.githubusercontent.com/octoleo/octojoom/refs/heads/${branch:-master}/src/octojoom" -o "$download" ||
        ! [ -s "$download" ] || ! grep -q '^#!/usr/bin/env bash$' "$download" || ! bash -n "$download"; then
      rm -f "$download"
      echo >&2 "ERROR: Update download or validation failed."
      return 1
    fi
    staged=$(sudo mktemp /usr/local/bin/.octojoom-update.XXXXXX) || {
      rm -f "$download"
      return 1
    }
    if [ -z "$staged" ] || ! sudo install -m 0755 "$download" "$staged" || ! sudo mv -f "$staged" /usr/local/bin/octojoom; then
      rm -f "$download"
      [ -z "$staged" ] || sudo rm -f "$staged"
      echo >&2 "ERROR: Update installation failed."
      return 1
    fi
    rm -f "$download"
    echo "SUCCESS: Update was successful."
    quitProgram
  fi
}

# Remove only a specific application directory, never a home or system root.
function validateOctojoomRemovalPath() {
  local directory="${1:-}" canonical protected
  [[ "$directory" == /* ]] && [ -d "$directory" ] || return 1
  canonical=$(cd "$directory" && pwd -P) || return 1
  case "$canonical" in
    /|/etc|/usr|/usr/local|/var|/home|/root|/opt|/srv|/tmp|/mnt|/media)
      echo >&2 "ERROR: Refusing to delete a system root: $directory"
      return 1
      ;;
  esac
  for protected in "$HOME" "${VDM_HOME_PATH:-}"; do
    [ -d "$protected" ] || continue
    protected=$(cd "$protected" && pwd -P) || return 1
    if [[ "$protected/" == "$canonical/"* ]]; then
      echo >&2 "ERROR: Refusing to delete a home directory or its parent: $directory"
      return 1
    fi
  done
  return 0
}

function removeOctojoomDirectory() {
  validateOctojoomRemovalPath "${1:-}" || return 1
  local directory="$1"
  sudo rm -rf -- "$directory"
}

# make an uninstall
function runUninstall() {
  if [[ $0 -ef /usr/bin/octojoom ]] && dpkg-query -S /usr/bin/octojoom >/dev/null 2>&1; then
    printf '%s\n' 'This installation is managed by APT. Use apt to upgrade or remove octojoom.' >&2
    return 1
  fi
  # little notice
  showNotice "We have three uninstall options: 1) Complete. 2) Just Script. 3) Make your selection."
  # first safety check
  if (whiptail --yesno "We are just trying to be careful here, therefore we have a few questions. Please remember there is an auto update option!\n\
    Are you absolutely sure you want to continue with the uninstalling process?\n(we need sudo privileges)" \
    --defaultno --title "Uninstalling ${PROGRAM_NAME} v${_VERSION} " --backtitle "${BACK_TITLE}" 15 112); then
    # we have four main options
    if (whiptail --yesno "Okay, So do you want to completely remove everything? This is the most dangerous option! IT CAN'T BE UNDONE!\
      We will remove literally everything like this script was never here." \
      --defaultno --title "Complete Uninstall of ${PROGRAM_NAME} v${_VERSION} " --backtitle "${BACK_TITLE}" 12 112); then
      local directory
      for directory in "$VDM_REPO_PATH" "$VDM_SRC_PATH" "$VDM_PROJECT_PATH"; do
        [ ! -d "$directory" ] || validateOctojoomRemovalPath "$directory" || return 1
      done
      if [ -d "${VDM_REPO_PATH}/joomla" ]; then
        # take down all joomla containers
        if hasDirectories 'joomla/enabled'; then
          downContainers 'joomla' || return 1
        fi
        # now completely remove Joomla configurations
        removeOctojoomDirectory "${VDM_REPO_PATH}/joomla" || return 1
      fi
      # Remove all of Openssh Docker stuff
      if [ -d "${VDM_REPO_PATH}/openssh" ]; then
        # take down all joomla containers
        if hasDirectories 'openssh/enabled'; then
          downContainers 'openssh' || return 1
        fi
        # now completely remove Joomla configurations
        removeOctojoomDirectory "${VDM_REPO_PATH}/openssh" || return 1
      fi
      # Remove all of Portainer Docker stuff
      if [ -d "${VDM_REPO_PATH}/portainer" ]; then
        # take down all portainer containers
        if [ -f "${VDM_REPO_PATH}/portainer/docker-compose.yml" ]; then
          disableContainer 'portainer' || return 1
        fi
        # now completely remove Portainer configurations
        removeOctojoomDirectory "${VDM_REPO_PATH}/portainer" || return 1
      fi
      # Remove all of Traefik Docker stuff
      if [ -d "${VDM_REPO_PATH}/traefik" ]; then
        # take down all traefik containers
        if [ -f "${VDM_REPO_PATH}/traefik/docker-compose.yml" ]; then
          disableContainer 'traefik' || return 1
        fi
        # now completely remove Traefik configurations
        removeOctojoomDirectory "${VDM_REPO_PATH}/traefik" || return 1
      fi
      # remove config if found
      if [ -d "${VDM_SRC_PATH}" ]; then
        removeOctojoomDirectory "${VDM_SRC_PATH}" || return 1
      fi
      # remove config if found
      if [ -d "${VDM_REPO_PATH}" ]; then
        removeOctojoomDirectory "${VDM_REPO_PATH}" || return 1
      fi
    elif (whiptail --yesno "Would you like to only remove the actual ${PROGRAM_NAME} v${_V}  script but keep all the Docker stuff?" \
      --title "Keep Docker Stuff" --backtitle "${BACK_TITLE}" 8 112); then
      # now remove the octojoom script
      if [ -f /usr/local/bin/octojoom ]; then
        sudo rm -f /usr/local/bin/octojoom || return 1
      fi
      # give the final message
      whiptail --title "${PROGRAM_NAME} v${_VERSION}  is UNINSTALLED" --msgbox "\n\
        ${PROGRAM_NAME}  v${_V} has been uninstalled.\n\n\
        We have not touched any of the Docker stuff.\n\
        To also remove these you will have to manually pull down the Docker containers (if there are any running) and then remove the following directories.\n\n\
        DOCKER:  ${VDM_REPO_PATH} \n\
        VOLUMES: ${VDM_PROJECT_PATH} \n\
        CONFIG:  ${VDM_SRC_PATH}" --backtitle "${BACK_TITLE}" 20 112
      # we exit here... where done!
      quitProgram
    else
      # little notice
      showNotice "This option lets you choose what you keep, so read the questions carefully! IT CAN'T BE UNDONE!"
      local directory
      for directory in "$VDM_REPO_PATH" "$VDM_SRC_PATH" "$VDM_PROJECT_PATH"; do
        [ ! -d "$directory" ] || validateOctojoomRemovalPath "$directory" || return 1
      done
      # shellcheck disable=SC1090
      # ----------------------------------------------------- MULTI CONTAINERS
      # Remove all of Joomla Docker stuff
      if [ -d "${VDM_REPO_PATH}/joomla" ] &&
        (whiptail --yesno "Would you like to completely remove the Joomla Docker yaml configurations in (${VDM_REPO_PATH}/joomla)?" \
          --defaultno --title "Remove Docker Config" --backtitle "${BACK_TITLE}" 12 112); then
        # take down all joomla containers
        if hasDirectories 'joomla/enabled'; then
          downContainers 'joomla' || return 1
        fi
        # now completely remove Joomla configurations
        removeOctojoomDirectory "${VDM_REPO_PATH}/joomla" || return 1
      fi
      # check if we have possible joomla containers (this will only run if they did not remove it above)
      if [ -e "${VDM_REPO_PATH}/joomla/enabled" ] &&
        (whiptail --yesno "Would you like to take down Joomla containers?" \
          --defaultno --title "Take Down Containers" --backtitle "${BACK_TITLE}" 8 112); then
        # take down all joomla containers
        if hasDirectories 'joomla/enabled'; then
          downContainers 'joomla' || return 1
        fi
        # remove all enabled
        removeOctojoomDirectory "${VDM_REPO_PATH}/joomla/enabled" || return 1
      fi
      # Remove all of Openssh Docker stuff
      if [ -d "${VDM_REPO_PATH}/openssh" ] &&
        (whiptail --yesno "Would you like to completely remove the Openssh Docker yaml configurations in (${VDM_REPO_PATH}/openssh)?" \
          --defaultno --title "Remove Docker Config" --backtitle "${BACK_TITLE}" 12 112); then
        # take down all joomla containers
        if hasDirectories 'openssh/enabled'; then
          downContainers 'openssh' || return 1
        fi
        # now completely remove Joomla configurations
        removeOctojoomDirectory "${VDM_REPO_PATH}/openssh" || return 1
      fi
      # check if we have possible openssh containers (this will only run if they did not remove it above)
      if [ -e "${VDM_REPO_PATH}/openssh/enabled" ] &&
        (whiptail --yesno "Would you like to take down Openssh containers?" \
          --defaultno --title "Take Down Containers" --backtitle "${BACK_TITLE}" 8 112); then
        # take down all joomla containers
        if hasDirectories 'openssh/enabled'; then
          downContainers 'openssh' || return 1
        fi
        # remove all enabled
        removeOctojoomDirectory "${VDM_REPO_PATH}/openssh/enabled" || return 1
      fi
      # ----------------------------------------------------- SINGLE CONTAINER
      # Remove all of Portainer Docker stuff
      if [ -d "${VDM_REPO_PATH}/portainer" ] &&
        (whiptail --yesno "Would you like to completely remove the Portainer Docker yaml configurations in (${VDM_REPO_PATH}/portainer)?" \
          --defaultno --title "Remove Docker Config" --backtitle "${BACK_TITLE}" 12 112); then
        # take down all portainer containers
        if [ -f "${VDM_REPO_PATH}/portainer/docker-compose.yml" ]; then
          disableContainer 'portainer' || return 1
        fi
        # now completely remove Portainer configurations
        removeOctojoomDirectory "${VDM_REPO_PATH}/portainer" || return 1
      fi
      # check if we have possible portainer container (this will only run if they did not remove it above)
      if [ -f "${VDM_REPO_PATH}/portainer/docker-compose.yml" ] &&
        (whiptail --yesno "Would you like to take down Portainer container?" \
          --defaultno --title "Take Down Container" --backtitle "${BACK_TITLE}" 8 112); then
        # take down the container
        disableContainer 'portainer' || return 1
      fi
      # Remove all of Traefik Docker stuff
      if [ -d "${VDM_REPO_PATH}/traefik" ] &&
        (whiptail --yesno "Would you like to completely remove the Traefik Docker yaml configurations in (${VDM_REPO_PATH}/traefik)?" \
          --defaultno --title "Remove Docker Config" --backtitle "${BACK_TITLE}" 12 112); then
        # take down all traefik containers
        if [ -f "${VDM_REPO_PATH}/traefik/docker-compose.yml" ]; then
          disableContainer 'traefik' || return 1
        fi
        # now completely remove Traefik configurations
        removeOctojoomDirectory "${VDM_REPO_PATH}/traefik" || return 1
      fi
      # check if we have possible traefik container (this will only run if they did not remove it above)
      if [ -f "${VDM_REPO_PATH}/traefik/docker-compose.yml" ] &&
        (whiptail --yesno "Would you like to take down Traefik container?" \
          --defaultno --title "Take Down Container" --backtitle "${BACK_TITLE}" 8 112); then
        # take down the container
        disableContainer 'traefik' || return 1
      fi
      # remove config if found
      if [ -d "${VDM_SRC_PATH}" ] &&
        (whiptail --yesno "Would you like to remove the global docker configurations?" \
          --defaultno --title "Remove Docker Config" --backtitle "${BACK_TITLE}" 8 112); then
        removeOctojoomDirectory "${VDM_SRC_PATH}" || return 1
      fi
    fi
    # now remove the octojoom script
    if [ -f /usr/local/bin/octojoom ]; then
      sudo rm -f /usr/local/bin/octojoom || return 1
    fi
    # last and final question as this is most dangerous and serious issue.
    if [ -d "${VDM_PROJECT_PATH}" ] &&
      (whiptail --yesno "Last question, would you like to remove all persistent volumes of your containers in (${VDM_PROJECT_PATH})?" \
        --defaultno --title "Completely DELETE persistent volumes" --backtitle "${BACK_TITLE}" 12 112); then
      removeOctojoomDirectory "${VDM_PROJECT_PATH}" || return 1
    fi
    # give the final message
    whiptail --title "${PROGRAM_NAME} v${_VERSION} is UNINSTALLED" --msgbox "\n\n\
      ${PROGRAM_NAME} v${_V} has been uninstalled." --backtitle "${BACK_TITLE}" 10 112
    # exit the program right now
    quitProgram
  fi
}

# we show the octoleo info quietly
octojoomQuietly() {
  local message
  # now set the message
  message="                                              https://git.vdm.dev/octoleo/octojoom

  Welcome to an Octoleo Program (${PROGRAM_NAME} v$_VERSION)

  Description
      With this script we can easily deploy docker containers of Joomla and Openssh.
      This combination of these tools give rise to a powerful and very secure shared
      development environment.
      This program has **command input** options as seen in the menus item called
      **Show command help**, but these commands are _not the only way_ to set these
      values. When the values are **omitted** you will be _asked in the terminal_ to
      manually enter the required values as needed. Furthermore, the use of
      **env variables** are also heavily used across the script. There are more
      than one .env file and the script will set those up for you whenever you run a
      task that make use of env variables. The script will check if those values exist,
      and if they don't it will ask for them, and store them automatically for future use.
      That same time the output message to the terminal will show you where the specific
      .env file can be found.

  Author                                        Licence
      Llewellyn van der Merwe <octoleo@vdm.io>      GNU GENERAL PUBLIC LICENSE Version 2

  --quiet"

  whiptail --msgbox "${message}" --fb --backtitle "${BACK_TITLE}" 32 112
}

# show the commands help menu
function showCommandsHelpMenu() {
  help=$(showHelp)
  whiptail --msgbox --scrolltext "${help}" --fb --backtitle "${BACK_TITLE}" 30 90
}

#####################################################################################################################VDM
######################################## MENUS

# show Joomla menu
function showJoomla() {
  local CHOICE
  while true; do
    # menu for dynamic addition
    local menu_options=()
    # our counter
    local i=3
    # load the back menu
    menu_options+=("back" "<-- Return to the main menu.")
    # setup new container
    menu_options+=("setup" "Setup new container")
    # enable existing container
    hasDirectories 'joomla/available' &&
      menu_options+=("enable" "Enable existing container") && i=$((i + 1))
    # disable enabled container
    hasDirectories 'joomla/enabled' &&
      menu_options+=("disable" "Disable enabled container") && i=$((i + 1))
    # take all enabled containers down
    hasDirectories 'joomla/enabled' &&
      menu_options+=("down" "Take all enabled containers down") && i=$((i + 1))
    # pull up all enabled containers
    hasDirectories 'joomla/enabled' &&
      menu_options+=("up" "Pull up all enabled containers") && i=$((i + 1))
    # edit available container
    isExpert && hasDirectories 'joomla/available' &&
      menu_options+=("edit" "Edit available container") && i=$((i + 1))
    # fix permissions
    hasDirectories '' "${VDM_PROJECT_PATH}" &&
      menu_options+=("fix" "Fix permissions of folders and files of a container") &&
      i=$((i + 1))
    # clone the project files (persistent volume) only
    hasDirectories '' "${VDM_PROJECT_PATH}" &&
      menu_options+=("clonefiles" "Clone project files") && i=$((i + 1))
    # clone a complete container (docker-compose.yml, .env values and project files)
    hasDirectories 'joomla/available' && hasDirectories '' "${VDM_PROJECT_PATH}" &&
      menu_options+=("clone" "Clone a container") && i=$((i + 1))
    # delete a container
    hasDirectories 'joomla/available' &&
      menu_options+=("delete" "Delete a container") && i=$((i + 1))
    # reset a volume
    isExpert && hasDirectories 'joomla/available' &&
      menu_options+=("reset" "Reset a volume") && i=$((i + 1))
    # Get Joomla env details
    isExpert && hasDirectories 'joomla/available' &&
      menu_options+=("joomla_env" "Open Joomla .env Details") && i=$((i + 1))
    # bulk deploy
    isExpert && menu_options+=("bulk" "Bulk deploy") && i=$((i + 1))
    # Quit Octoleo Program
    menu_options+=("quit" "Quit ${PROGRAM_NAME}")
    # get the selection
    CHOICE=$(
      whiptail --menu "Make your selection" 23 112 $i \
        --title "Joomla | ${PROGRAM_NAME} v${_V}" --fb \
        --backtitle "${BACK_TITLE}" --nocancel --notags \
        "${menu_options[@]}" 3>&2 2>&1 1>&3
    ) || return $?

    # menu actions
    case $CHOICE in
    "setup")
      setupContainer 'joomla'
      ;;
    "edit")
      editContainer 'joomla'
      ;;
    "enable")
      enableContainer 'joomla'
      ;;
    "disable")
      disableContainer 'joomla'
      ;;
    "down")
      downContainers 'joomla'
      ;;
    "up")
      upContainers 'joomla'
      ;;
    "fix")
      fixContainersPermissions
      ;;
    "clonefiles")
      cloneProjectFiles 'joomla'
      ;;
    "clone")
      cloneContainer 'joomla'
      ;;
    "delete")
      deleteContainer 'joomla'
      ;;
    "reset")
      resetContainer 'joomla'
      ;;
    "joomla_env")
      openEnv 'joomla'
      ;;
    "bulk")
      bulkSetupContainers 'joomla'
      ;;
    "quit") quitProgram ;;
    esac

    # menu loop
    case $CHOICE in
    "setup" | "edit" | "enable" | "disable" | "down" | "up" | "fix" | "clonefiles" | "clone" | "delete" | "reset" | "joomla_env" | "bulk")
      continue
      ;;
    *) return 0 ;;
    esac
  done
}

# show Openssh menu
function showOpenssh() {
  local CHOICE
  while true; do
    # menu for dynamic addition
    local menu_options=()
    # our counter
    local i=3
    # load the back menu
    menu_options+=("back" "<-- Return to the main menu.")
    # setup new container
    menu_options+=("setup" "Setup new container")
    # enable existing container
    hasDirectories 'openssh/available' &&
      menu_options+=("enable" "Enable existing container") && i=$((i + 1))
    # disable enabled container
    hasDirectories 'openssh/enabled' &&
      menu_options+=("disable" "Disable enabled container") && i=$((i + 1))
    # take all enabled containers down
    hasDirectories 'openssh/enabled' &&
      menu_options+=("down" "Take all enabled containers down") && i=$((i + 1))
    # pull up all enabled containers
    hasDirectories 'openssh/enabled' &&
      menu_options+=("up" "Pull up all enabled containers") && i=$((i + 1))
    # edit available container
    isExpert && hasDirectories 'openssh/available' &&
      menu_options+=("edit" "Edit available container") && i=$((i + 1))
    # delete a container
    hasDirectories 'openssh/available' &&
      menu_options+=("delete" "Delete a container") && i=$((i + 1))
    # Get Openssh env details
    isExpert && hasDirectories 'openssh/available' &&
      menu_options+=("openssh_env" "Open Openssh .env Details") && i=$((i + 1))
    # Quit Octoleo Program
    menu_options+=("quit" "Quit ${PROGRAM_NAME}")
    # get the selection
    CHOICE=$(
      whiptail --menu "Make your selection" 20 112 $i \
        --title "Openssh | ${PROGRAM_NAME} v${_V}" --fb \
        --backtitle "${BACK_TITLE}" --nocancel --notags \
        "${menu_options[@]}" 3>&2 2>&1 1>&3
    ) || return $?

    case $CHOICE in
    "setup")
      setupContainer 'openssh'
      ;;
    "edit")
      editContainer 'openssh'
      ;;
    "enable")
      enableContainer 'openssh'
      ;;
    "disable")
      disableContainer 'openssh'
      ;;
    "down")
      downContainers 'openssh'
      ;;
    "up")
      upContainers 'openssh'
      ;;
    "delete")
      deleteContainer 'openssh'
      ;;
    "openssh_env")
      openEnv 'openssh'
      ;;
    "quit") quitProgram ;;
    esac

    # menu loop
    case $CHOICE in
    "setup" | "edit" | "enable" | "disable" | "down" | "up" | "delete" | "openssh_env" )
      continue
      ;;
    *) return 0 ;;
    esac
  done
}

# show Traefik menu
function showTraefik() {
  local CHOICE
  while true; do
    # menu for dynamic addition
    local menu_options=()
    # our counter
    local i=3
    # load the back menu
    menu_options+=("back" "<-- Return to the main menu.") && i=$((i + 1))
    # setup new container
    menu_options+=("setup" "Setup or rebuild Traefik")
    # enable existing container
    [ -f "${VDM_REPO_PATH}/traefik/docker-compose.yml" ] &&
      menu_options+=("enable" "Enable Traefik") && i=$((i + 1))
    # disable enabled container
    [ -f "${VDM_REPO_PATH}/traefik/docker-compose.yml" ] &&
      menu_options+=("disable" "Disable Traefik") && i=$((i + 1))
    # edit available container
    isExpert && [ -f "${VDM_REPO_PATH}/traefik/docker-compose.yml" ] &&
      menu_options+=("edit" "Edit Traefik") && i=$((i + 1))
    # delete traefik container
    [ -f "${VDM_REPO_PATH}/traefik/docker-compose.yml" ] &&
      menu_options+=("delete" "Delete Traefik") && i=$((i + 1))
    # set network if not set
    isExpert && menu_options+=("network" "Set Network") && i=$((i + 1))
    # Quit Octoleo Program
    menu_options+=("quit" "Quit ${PROGRAM_NAME}")
    # get the selection
    CHOICE=$(
      whiptail --menu "Make your selection" 20 112 $i \
        --title "Traefik | ${PROGRAM_NAME} v${_V}" --fb \
        --backtitle "${BACK_TITLE}" --nocancel --notags \
        "${menu_options[@]}" 3>&2 2>&1 1>&3
    ) || return $?

    # menu actions
    case $CHOICE in
    "setup")
      setupContainer 'traefik'
      ;;
    "edit")
      editContainer 'traefik'
      ;;
    "enable")
      enableContainer 'traefik'
      ;;
    "disable")
      disableContainer 'traefik'
      ;;
    "delete")
      deleteContainer 'traefik'
      ;;
    "network")
      setNetworks
      ;;
    "quit") quitProgram ;;
    esac

    # menu loop
    case $CHOICE in
    "setup" | "edit" | "enable" | "disable" | "delete" | "network")
      continue
      ;;
    *) return 0 ;;
    esac
  done
}

# show Portainer menu
function showPortainer() {
  local CHOICE
  while true; do
    # menu for dynamic addition
    local menu_options=()
    # our counter
    local i=3
    # load the back menu
    menu_options+=("back" "<-- Return to the main menu.")
    # setup new container
    menu_options+=("setup" "Setup or rebuild Portainer")
    # enable existing container
    [ -f "${VDM_REPO_PATH}/portainer/docker-compose.yml" ] &&
      menu_options+=("enable" "Enable Portainer") && i=$((i + 1))
    # disable enabled container
    [ -f "${VDM_REPO_PATH}/portainer/docker-compose.yml" ] &&
      menu_options+=("disable" "Disable Portainer") && i=$((i + 1))
    # edit available container
    isExpert && [ -f "${VDM_REPO_PATH}/portainer/docker-compose.yml" ] &&
      menu_options+=("edit" "Edit Portainer") && i=$((i + 1))
    # delete traefik container
    [ -f "${VDM_REPO_PATH}/portainer/docker-compose.yml" ] &&
      menu_options+=("delete" "Delete Portainer") && i=$((i + 1))
    # Quit Octoleo Program
    menu_options+=("quit" "Quit ${PROGRAM_NAME}")
    # get the selection
    CHOICE=$(
      whiptail --menu "Make your selection" 20 112 $i \
        --title "Portainer | ${PROGRAM_NAME} v${_V}" --fb \
        --backtitle "${BACK_TITLE}" --nocancel --notags \
        "${menu_options[@]}" 3>&2 2>&1 1>&3
    ) || return $?

    # menu actions
    case $CHOICE in
    "setup")
      setupContainer 'portainer'
      ;;
    "edit")
      editContainer 'portainer'
      ;;
    "enable")
      enableContainer 'portainer'
      ;;
    "disable")
      disableContainer 'portainer'
      ;;
    "delete")
      deleteContainer 'portainer'
      ;;
    "quit") quitProgram ;;
    esac

    # menu loop
    case $CHOICE in
    "setup" | "edit" | "enable" | "disable" | "delete")
      continue
      ;;
    *) return 0 ;;
    esac
  done
}

# show systems help menu
function showSettings() {
  local CHOICE
  while true; do
    # menu for dynamic addition
    local menu_options=()
    # our counter
    local i=8
    # load the back menu
    menu_options+=("back" "<-- Return to the main menu.")
    # the mode switch
    isExpert && menu_options+=("basic-mode" "Switch to basic mode")
    ! isExpert && menu_options+=("expert-mode" "Switch to expert mode")
    i=$((i + 1))
    # Show command help
    menu_options+=("command-help" "Help with commands")
    # Show folder paths
    menu_options+=("important-paths" "Important paths")
    # Edit the global config
    isExpert && [ -f "${VDM_SRC_PATH}/.env" ] &&
      menu_options+=("edit-config" "Edit Config") && i=$((i + 1))
    # the remote-control option
    isExpert && menu_options+=("remote" "Access Remote ${PROGRAM_NAME}") && i=$((i + 1))
    # Report an Issue
    menu_options+=("report-issue" "Report an issue")
    # Update the whole script
    menu_options+=("update" "Update ${PROGRAM_NAME,,}")
    # Uninstall the whole script
    menu_options+=("uninstall" "Uninstall ${PROGRAM_NAME,,}")
    # Octoleo details
    menu_options+=("octojoom" "${PROGRAM_NAME}")
    # Quit Octoleo Program
    menu_options+=("quit" "Quit ${PROGRAM_NAME}")
    # get the selection
    CHOICE=$(
      whiptail --menu "Make your selection" 20 112 $i \
        --title "Settings Menu | ${PROGRAM_NAME} v${_V}" --fb \
        --backtitle "${BACK_TITLE}" --nocancel --notags \
        "${menu_options[@]}" 3>&2 2>&1 1>&3
    ) || return $?

    # menu actions
    case $CHOICE in
    "basic-mode")
      setMode 'basic'
      ;;
    "expert-mode")
      setMode 'expert'
      ;;
    "command-help")
      showCommandsHelpMenu
      ;;
    "important-paths")
      showImportantPaths
      ;;
    "edit-config")
      editConfigFile
      ;;
    "remote")
      hasRemoteSystemSet && connectToRemoteSystem
      ;;
    "report-issue")
      showLink "https://git.vdm.dev/octoleo/octojoom/issues" "To report an issue go to:" "Report an Issue"
      ;;
    "update")
      runUpdate
      ;;
    "uninstall")
      runUninstall
      ;;
    "octojoom")
      octojoomQuietly
      ;;
    "quit") quitProgram ;;
    esac

    # menu loop
    case $CHOICE in
    "basic-mode" | "expert-mode" | "command-help" | "important-paths" | "edit-config" | "report-issue" | "octojoom" | "remote")
      continue
      ;;
    *) return 0 ;;
    esac
  done
}

# show domains menu
function domainsMenu() {
  local CHOICE
  while true; do
    # menu for dynamic addition
    local menu_options=()
    # our counter
    local i=3
    # load the back menu
    menu_options+=("back" "<-- Return to the main menu.")
    # add more domains
    allowMultiDomains &&
      menu_options+=("add" "Add Domain") && i=$((i + 1))
    # remove existing domains
    [ -f "${VDM_SRC_PATH}/.domains" ] &&
      menu_options+=("delete" "Delete Domain") && i=$((i + 1))
    # edit available container
    isExpert && allowEditHostFile &&
      menu_options+=("edit" "Edit Host File") && i=$((i + 1))
    # Quit Octoleo Program
    menu_options+=("quit" "Quit ${PROGRAM_NAME}")
    # get the selection
    CHOICE=$(
      whiptail --menu "Make your selection" 20 112 $i \
        --title "Domains Menu | ${PROGRAM_NAME} v${_V}" --fb \
        --backtitle "${BACK_TITLE}" --nocancel --notags \
        "${menu_options[@]}" 3>&2 2>&1 1>&3
    ) || return $?

    # menu actions
    case $CHOICE in
    "add")
      setMultiDomains
      ;;
    "delete")
      deleteMultiDomains
      ;;
    "edit")
      editHostFile
      ;;
    "quit") quitProgram ;;
    esac

    # menu loop
    case $CHOICE in
    "add" | "delete" | "edit")
      continue
      ;;
    *) return 0 ;;
    esac
  done
}

# show migration menu
function migrateMenu() {
  local CHOICE
  while true; do
    # menu for dynamic addition
    local menu_options=()
    # our counter
    local i=4
    # load the back menu
    menu_options+=("back" "<-- Return to the main menu.")
    # Select a joomla container to migrate
    menu_options+=("joomla" "Migrate Complete Joomla Project")
    isExpert && menu_options+=("joomlafiles" "Transfer Joomla Compose Folder Only") && i=$((i + 1))
    # Select a openssh container to migrate
    menu_options+=("openssh" "Migrate Openssh Container")
    # Select project directories to migrate
    hasDirectories '' "${VDM_PROJECT_PATH}" &&
        menu_options+=("directory" "Migrate Project Directory") && i=$((i + 1))
    # the remote-control option
    isExpert && menu_options+=("remote" "Access Remote ${PROGRAM_NAME}") && i=$((i + 1))
    # Quit Octoleo Program
    menu_options+=("quit" "Quit ${PROGRAM_NAME}")
    # get the selection
    CHOICE=$(
      whiptail --menu "Make your selection" 20 112 $i \
        --title "Migration Menu | ${PROGRAM_NAME} v${_V}" --fb \
        --backtitle "${BACK_TITLE}" --nocancel --notags \
        "${menu_options[@]}" 3>&2 2>&1 1>&3
    ) || return $?

    # menu actions
    case $CHOICE in
    "joomla")
      migrateContainer 'joomla'
      ;;
    "joomlafiles")
      VDM_CONTAINER_TYPE=joomla
      joomla__TRuST__migratefiles
      ;;
    "openssh")
      migrateContainer 'openssh'
      ;;
    "directory")
      migrateContainer 'directory'
      ;;
    "remote")
      connectToRemoteSystem
      ;;
    "quit") quitProgram
      ;;
    esac

    # menu loop
    case $CHOICE in
    "joomla" | "joomlafiles" | "openssh" | "directory" | "remote")
      continue
      ;;
    *) return 0 ;;
    esac
  done
}

# MAIN MENU
function mainMenu() {
  local CHOICE
  # get the selection
  while true; do
    # menu for dynamic addition
    local menu_options=()
    # our counter
    local i=6
    # Joomla containers
    menu_options+=("joomla" "Joomla Containers")
    # Openssh containers
    menu_options+=("openssh" "Openssh Containers")
    # Traefik container
    menu_options+=("traefik" "Traefik Container")
    # Portainer container
    menu_options+=("portainer" "Portainer Container")
    # Manage Domains
    if isExpert && (allowEditHostFile || allowMultiDomains); then
      menu_options+=("domains" "Manage Domains")
      i=$((i + 1))
    fi
    # Migrate available container
    isExpert &&
      menu_options+=("migrate" "Migration Options") && i=$((i + 1))
    # Delete Persistent Volumes
    isExpert && hasDirectories '' "${VDM_PROJECT_PATH}" &&
      menu_options+=("delete" "Delete Persistent Volumes") && i=$((i + 1))
    # Octoleo settings
    menu_options+=("settings" "${PROGRAM_NAME} Settings")
    # Quit Octoleo Program
    menu_options+=("quit" "Quit ${PROGRAM_NAME}")

    CHOICE=$(
      whiptail --menu "Make your selection" 20 112 $i \
        --title "${PROGRAM_NAME} v${_V}" --fb \
        --backtitle "${BACK_TITLE}" --nocancel --notags \
        "${menu_options[@]}" 3>&2 2>&1 1>&3
    ) || return $?

    case $CHOICE in
    "joomla")
      showJoomla
      ;;
    "openssh")
      showOpenssh
      ;;
    "traefik")
      showTraefik
      ;;
    "portainer")
      showPortainer
      ;;
    "domains")
      domainsMenu
      ;;
    "migrate")
      hasRemoteSystemSet && migrateMenu
      ;;
    "delete")
      deletePersistentVolumes
      ;;
    "settings")
      showSettings
      ;;
    "quit") quitProgram ;;
    esac
  done
}

#####################################################################################################################VDM
######################################## GENERAL SHARED FUNCTIONS

# show error
function showError() {
  whiptail --title "ERROR | ${PROGRAM_NAME} v${_V}" --backtitle "${BACK_TITLE}" \
    --msgbox "${1}" "${2:-12}" 112
}

# show info
function showInfo() {
  whiptail --title "INFO | ${PROGRAM_NAME} v${_V}" --backtitle "${BACK_TITLE}" \
    --infobox "${1}" "${2:-12}" 112
}

# show notice
function showNotice() {
  whiptail --title "NOTICE | ${PROGRAM_NAME} v${_V}" --backtitle "${BACK_TITLE}" \
    --msgbox "${1}" "${2:-12}" 112
}

# show link
function showLink() {
  whiptail --title "${3:-Open Link} | ${PROGRAM_NAME} v${_V}" --backtitle "${BACK_TITLE}" \
    --msgbox "${2:-To open the link click here:} ${1}" 8 112
}

# show progress bar
function showProgress() {
  # some locals
  local title
  local message
  local per
  # get input
  message="$1"
  title="${2:-Please wait!}"
  # our little loop progress
  {
    per=1
    while (true); do
      if ! inProgress; then
        # we are finished, so we slow down to 100%
        sleep .2
        echo 88
        sleep .2
        echo 90
        sleep .$((1 + "$RANDOM" % 6))
        echo 98
        sleep .$((1 + "$RANDOM" % 5))
        echo 100
        sleep .$((1 + "$RANDOM" % 5))
        break
      elif [[ "87" -eq "$per" ]]; then
        # if it takes longer we loop
        per="33"
      fi
      # sleep a little moment
      sleep .$((1 + "$RANDOM" % 9))
      echo $per
      per=$((per + 1))
    done
  } | whiptail --title "${title}" --gauge "${message}" --backtitle "${BACK_TITLE}" 8 112 0
}

# turn on progress
function progressSwitchOn() {
  echo "Progress ON" >"${VDM_SRC_PATH}/.progress"
}

# switch off the progress
function progressSwitchOff() {
  rm -f "${VDM_SRC_PATH}/.progress"
}

# get the progress
function inProgress() {
  if [ -f "${VDM_SRC_PATH}/.progress" ]; then
    # found it
    return 0
  fi
  # did not find it
  return 1
}

# show important paths
function showImportantPaths() {
  local message
  # now set the message
  message="                                                                      ${PROGRAM_NAME} v$_VERSION

  We have a few important paths that you should know, and use to manually manage your setup.

    DOCKER:  ${VDM_REPO_PATH}
    SOURCE:  ${VDM_SRC_PATH}/.images-source
    DOMAINS: ${VDM_SRC_PATH}/.domains
    CONFIG:  ${VDM_SRC_PATH}/.env
    SSH:     ${VDM_REPO_PATH}/openssh/.ssh
    VOLUMES: ${VDM_PROJECT_PATH}

  Then we have some key environment variable files that hold very useful and important information.
  Since we do not store any passwords or other important details in the docker-compose.yml files
  they are stored in >>these environment variable files<< and therefore we set these .env file
  permission to (600) for security.

    JOOMLA:    ${VDM_REPO_PATH}/joomla/.env
    OPENSSH:   ${VDM_REPO_PATH}/openssh/.env
    TRAEFIK:   ${VDM_REPO_PATH}/traefik/.env
    PORTAINER: ${VDM_REPO_PATH}/portainer/.env


  Not all these files or folders may exist, they are created only when needed.
"

  whiptail --msgbox "${message}" --fb --backtitle "${BACK_TITLE}" 32 112
}

# show show the Joomla config details
function showJoomlaConfigDetails() {
  # load the env back to show if set previously
  # shellcheck disable=SC1090
  # [ -f "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/.env" ] && source "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/.env"
  # set some locals
  local message
  # now set the message
  message="                                                                      ${PROGRAM_NAME} v$_VERSION

  Running the Joomla container for the first time you will need these details:
  --------------------------------------------------------------------
    URL:              ${VDM_HTTP_SCHEME}${VDM_SUBDOMAIN}.${VDM_DOMAIN}
    DATABASE_HOST:    mariadb${VDM_KEY}:3306
  --------------------------------------------------------------------
    VDM_${VDM_ENV_KEY^^}_DB:       ${vdm_database_name}
    VDM_${VDM_ENV_KEY^^}_DB_USER:  ${vdm_database_user}
    VDM_${VDM_ENV_KEY^^}_DB_PASS:  ${vdm_database_pass}
    VDM_${VDM_ENV_KEY^^}_DB_ROOT:  ${vdm_database_rootpass}
  --------------------------------------------------------------------
  These details are securely stored in this environment variable file
    ${VDM_REPO_PATH}/joomla/.env
  --------------------------------------------------------------------

  Do not remove these details from the file, as it's used to deploy the container.
"

  whiptail --msgbox "${message}" --fb --backtitle "${BACK_TITLE}" 30 112
}

# we must get a random key
function getRandomPass() {
  getRandomString "${1:-128}" 'A-HJ-NP-Za-km-z2-9'
}

# we must get a random key
function getRandomName() {
  getRandomString "${1:-128}" 'A-Za-z'
}

# Read finite chunks so the random producer always terminates. C locale makes
# arbitrary random bytes safe for BSD tr; avoiding tr | head also avoids SIGPIPE.
function getRandomString() {
  local length="${1:-128}" alphabet="$2" result='' chunk
  if [[ ! "$length" =~ ^[1-9][0-9]{0,4}$ ]] || [ "$length" -gt 65536 ]; then
    printf 'Random string length must be between 1 and 65536.\n' >&2
    return 1
  fi
  while [ "${#result}" -lt "$length" ]; do
    chunk=$(set -o pipefail; LC_ALL=C head -c 1024 /dev/urandom | LC_ALL=C tr -dc "$alphabet") || return 1
    result+="$chunk"
  done
  printf '%s' "${result:0:length}"
}

# Get input from the user using whiptail utility
# $1: Prompt message
# $2 (optional): Default input value
# $3 (optional): Title for the input dialog
function getInput() {
  # set local var
  local answer
  # get the answer
  answer=$(whiptail --inputbox "$1" 10 112 "${2:-}" --title "${3:-Get Input}" \
    --backtitle "${BACK_TITLE}" --nocancel 3>&1 1>&2 2>&3) || return $?
  # return the answer
  printf '%s\n' "${answer}"
}

# Display a yes/no prompt using the whiptail utility.
# If "defaultno" is passed as the fifth parameter, it defaults to "No" when VDM_FORCE is set to "true".
# $1: Prompt message
# $2 (optional): Title for the dialog (default: "Confirmation Required")
# $3 (optional): Height of the dialog (default: 8)
# $4 (optional): Width of the dialog (default: 50)
# $5 (optional): Set to "defaultno" to make "No" the default choice.
# Returns 0 (yes) if the user selects "Yes".
# Returns 1 (no) if the user selects "No" or if "defaultno" is set and VDM_FORCE is "true".
function getInputYesNo() {
  # set local vars
  local question="$1"
  local title="${2:-Confirmation Required}"
  local height="${3:-8}"
  local width="${4:-50}"
  local defaultno="${5:-}"

  # Handle VDM_FORCE behavior based on the 'defaultno' parameter
  if [ "$VDM_FORCE" = "true" ]; then
    if [ "$defaultno" = "defaultno" ]; then
      return 1  # Default to No if "defaultno" is set and VDM_FORCE is true
    else
      return 0  # Default to Yes if "defaultno" is not set and VDM_FORCE is true
    fi
  else
    # Display the whiptail prompt with the provided parameters
    if [ "$defaultno" = "defaultno" ]; then
      whiptail --defaultno --yesno "$question" "$height" "$width" --title "$title" \
        --backtitle "${BACK_TITLE}" 3>&1 1>&2 2>&3
    else
      whiptail --yesno "$question" "$height" "$width" --title "$title" \
        --backtitle "${BACK_TITLE}" 3>&1 1>&2 2>&3
    fi
  fi
}

# get the input until is gotten
function getInputNow() {
  local message
  local default
  local title
  local answer=""
  # get the values
  message="${1:-Enter a value}"
  default="${2:-}"
  title="${3:-value}"
  # get the value if not already set
  while [ -z "$answer" ] || [ ${#answer} -le 1 ]; do
    # get the value
    answer=$(getInput "${message}" \
      "${default}" "${title}") || return $?
    # keep asking if empty or does exist
    if [ ${#answer} -le 1 ]; then
      showError "You must enter a $title"
    fi
  done
  # return the answer
  printf '%s\n' "${answer}"
}

# get a selected directory
function getSelectedDirectory() {
  # the selected folder
  local answer
  #  set the local path
  local path="${2:-}"
  # set local var
  local folder="${3:-}"
  # we start the selection array
  local selected=()
  # our counter
  local i=0
  # whiptail box size details
  local description_lines
  local height
  # now check if this dir has sub dirs
  if hasDirectories '' "$path"; then
    # loop over the directory
    local dir_
    for dir_ in "${path%/}/"* "${path%/}/".[!.]* "${path%/}/"..?*; do
      [ -d "$dir_" ] || continue
      # remove the full path
      dir_="${dir_##*/}"
      # load the selection
      [ "$folder" = "${dir_#/}" ] && selected+=("${dir_#/}" "${dir_#/}" "ON") || selected+=("${dir_#/}" "${dir_#/}" "OFF")
      # increment our pointer
      if [ "$i" -le 10 ]; then
        i=$((i + 1))
      fi
    done

    # Calculate the height based on the description length and directory count
    description_lines=$(echo -e "${1}" | wc -l)
    height=$((description_lines + i + 7))

    # now make the selection
    answer=$(whiptail --title "${4:-Make a Selection}" --radiolist \
      "${1}" $height 112 $i \
      "${selected[@]}" --backtitle "${BACK_TITLE}" --nocancel --notags 3>&1 1>&2 2>&3) || return $?
  fi
  # return the answer
  printf '%s\n' "${answer:-$folder}"
}

# select multiple directories from one directory
function getSelectedDirectories() {
  # the selected folder
  local answer
  #  set the local path
  local path="${2:-}"
  # we start the selection array
  local selected=()
  # our counter
  local i=0
  # whiptail box size details
  local description_lines
  local height
  # now check if this dir has sub dirs
  if hasDirectories '' "$path"; then
    # loop over the directory
    local dir_
    for dir_ in "${path%/}/"* "${path%/}/".[!.]* "${path%/}/"..?*; do
      [ -d "$dir_" ] || continue
      # remove the full path
      dir_="${dir_##*/}"
      # load the selection
      selected+=("${dir_#/}" "${dir_#/}" "OFF")
      # increment our pointer
      if [ "$i" -le 10 ]; then
        i=$((i + 1))
      fi
    done

    # Calculate the height based on the description length and directory count
    description_lines=$(echo -e "${1}" | wc -l)
    height=$((description_lines + i + 7))

    # now make the selection
    answer=$(whiptail --title "${3:-Make a Selection}" --checklist\
      "${1}" $height 112 $i \
      "${selected[@]}" --backtitle "${BACK_TITLE}" --nocancel --notags 3>&1 1>&2 2>&3) || return $?
    # return the answer
    printf '%s\n' "${answer}"
  else
    echo ''
  fi
}

# create a yml new line with 3 indents
function getYMLine3() {
  # return line
  cat <<EOF

      ${1}
EOF
}

# create a yml new line with 2 indents
function getYMLine2() {
  # return line
  cat <<EOF

    ${1}
EOF
}

# create a yml new line with 1 indent
function getYMLine1() {
  # return line
  cat <<EOF

  ${1}
EOF
}

# get input from user
function getPassword() {
  # set local var
  local PASSWORD
  # get the pass
  PASSWORD=$(whiptail --passwordbox "$1" 10 112 "${2:-}" --title "${3:-Get Password}" \
    --backtitle "${BACK_TITLE}" --nocancel 3>&1 1>&2 2>&3) || return $?
  # return the password
  printf '%s\n' "${PASSWORD}"
}

# get the target branch to use in update
function getTargetBranch() {
  local answer
  # now make the selection
  answer=$(whiptail --title "Select Update Channel" \
    --radiolist  --backtitle "${BACK_TITLE}" --nocancel --notags \
    "You can select the update channel you would like to use." 10 80 2 \
    "master" "Stable Version" "ON" \
    "staging" "Developer Version" "OFF" \
    3>&1 1>&2 2>&3) || return $?
  # return the answer (default master)
  echo "${answer:-master}"
}

# get the target repository to use in update
function getImageSource() {
  # we set some local stuff
  local image
  local image_source
  local images_source
  local default
  local default_joomengine
  local default_octojoom
  local image_name image_desc
  # menu for dynamic addition
  local menu_options=()
  # our counter
  local i=3
  # set the defaults
  default="joomla|https://hub.docker.com/_/joomla?tab=tags;https://raw.githubusercontent.com/joomla-docker/docker-joomla/master/docker-entrypoint.sh"
  default_joomengine="octoleo/joomengine|https://hub.docker.com/r/octoleo/joomengine/tags;https://raw.githubusercontent.com/octoleo/joomengine/refs/heads/master/src/docker/docker-entrypoint.sh"
  default_octojoom="llewellyn/joomla|https://hub.docker.com/r/llewellyn/joomla/tags;https://raw.githubusercontent.com/octoleo/docker-joomla/refs/heads/octoleo/docker-entrypoint.sh"
  # we only ask if we are in expert mode
  if isExpert; then
    # set the base images source
    menu_options+=("${default}" "Joomla official image" "OFF")
    menu_options+=("${default_joomengine}" "JoomEngine official image" "OFF")
    menu_options+=("${default_octojoom}" "Octoleo Joomla image" "OFF")
    # get existing source
    if [ -f "${VDM_SRC_PATH}/.images-source" ] && readarray -t images_source <"${VDM_SRC_PATH}/.images-source"; then
      # build the menus
      if [ "${#images_source[@]}" -gt 0 ]; then
        # loop source images
        for image in "${images_source[@]}"; do
          # the image name (get before first comma)
          image_name="${image%%,*}"
          # the image description (get after last comma)
          image_desc="${image##*,}"
          # make sure we have a value, and it is not the defaults already set
          if [ "${#image_name}" -ge 1 ] && [ "${#image_desc}" -ge 1 ] &&
            [ "${image_name}" != "${default}" ] &&
            [ "${image_name}" != "${default_joomengine}" ] &&
            [ "${image_name}" != "${default_octojoom}" ]; then
            # load the source name and description
            menu_options+=("${image_name}" "${image_desc}" "OFF")
            # increment our counter
            i=$((i + 1))
          fi
        done
      fi
    fi
    # now make the selection
    image_source=$(whiptail --title "Select image source repository" \
      --radiolist --backtitle "${BACK_TITLE}" --nocancel --notags \
      "You can select the source of your Joomla! image." 10 80 $i \
      "${menu_options[@]}" 3>&1 1>&2 2>&3) || return $?
  fi
  # return the answer (default joomla)
  echo "${image_source:-$default}"
}

# get a list of domains locally set
function getListDomains() {
  # get the separator
  local separator="${1}"
  # menu for dynamic addition
  local menu_options=()
  local domains
  # get existing domains
  if [ -f "${VDM_SRC_PATH}/.domains" ] && readarray -t domains <"${VDM_SRC_PATH}/.domains"; then
    # check that we have values
    if [ "${#domains[@]}" -gt 0 ]; then
      # build the menu
      for domain in "${domains[@]}"; do
        # load the back menu
        [ "${#domain}" -ge 1 ] && menu_options+=("${domain}")
      done
      # we show a list of options including the option to add another
      for domain in "${menu_options[@]}"; do
        printf '%b%s' "$separator" "$domain"
      done
      printf '\n'
    fi
  fi
}

# to set a global multiple domains file and values
function getMultiDomain() {
  # we set some local stuff
  local domain_name
  local domains
  # menu for dynamic addition
  local menu_options=()
  # our counter
  local i=0
  # always add the main domain or (default) first
  # so we should always have a selection
  saveMultiDomain "${VDM_DOMAIN}" || return $?
  # now clear the main domain (in case we use getDomain)
  unset VDM_DOMAIN
  # get existing domains
  if [ -f "${VDM_SRC_PATH}/.domains" ] && readarray -t domains <"${VDM_SRC_PATH}/.domains"; then
    # build the menu
    if [ "${#domains[@]}" -gt 0 ]; then
      # loop domains
      for domain in "${domains[@]}"; do
        # load the domain if it has a length
        [ "${#domain}" -ge 1 ] && menu_options+=("${domain}" "${domain}" "OFF")
        # increment our counter
        [ "${#domain}" -ge 1 ] && i=$((i + 1))
      done
      # make sure we have domains
      if [ "${#menu_options[@]}" -gt 0 ]; then
        # we show a list of options including the option to add another
        domain_name=$(whiptail --title "Select a Domain" \
          --radiolist --backtitle "${BACK_TITLE}" --nocancel --notags \
          "Select a domain, or none to add another." 30 80 $i \
          "${menu_options[@]}" 3>&1 1>&2 2>&3) || return $?
      fi
    fi
  fi
  # check if we have a selection
  if [ "${domain_name:-none}" = 'none' ]; then
    # we must let them enter the new domain name
    getDomain 'Enter a domain name' 'Enter a Domain Name' || return $?
  else
    # set the new main domain
    VDM_DOMAIN="${domain_name}"
    # update the main domain
    export VDM_DOMAIN
  fi
  # add for next time
  saveMultiDomain "${VDM_DOMAIN}"
}

# Validate DNS labels before using domains in Compose labels or host files.
function isValidDomain() {
  local domain="$1" label
  local labels=()
  [[ "$domain" =~ ^[a-zA-Z0-9.-]+$ ]] || return 1
  [ "${#domain}" -le 253 ] && [[ "$domain" == *.* ]] || return 1
  [[ "$domain" != .* && "$domain" != *. && "$domain" != *..* ]] || return 1
  IFS='.' read -r -a labels <<< "$domain"
  for label in "${labels[@]}"; do
    [ "${#label}" -le 63 ] && [[ "$label" =~ ^[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?$ ]] || return 1
  done
}

# set the VDM domain value
function getDomain() {
  # set some locals
  local message="Enter main domain name"
  local title="Enter Main Domain"
  local tld="${VDM_CONTAINER_TYPE:-vdm}"
  # get the arg passed if any
  message="${1:-$message}"
  title="${2:-$title}"
  # get the VDM Domain value if not already set
  while ! isValidDomain "${VDM_DOMAIN:-}"; do
    # get the value
    VDM_DOMAIN=$(getInput "${message}\n[must have at least one dot]" \
      "${USER:-octoleo}.${tld,,}" "${title}") || return $?
    # keep asking if empty or does exist
    if [ ${#VDM_DOMAIN} -le 1 ]; then
      showError "You must enter a domain name!"
    elif [[ "${VDM_DOMAIN}" != *.* ]]; then
      showError "You must enter a domain name with at least one dot"
    elif ! isValidDomain "$VDM_DOMAIN"; then
      showError "Enter a valid domain with labels of 1 to 63 letters, digits or internal hyphens."
    fi
  done
  # update the main domain
  export VDM_DOMAIN
}

# set the main domain
function getMainDomain() {
  # we first check if we have a main domain passed as command argument
  if [ "${VDM_ARG_DOMAIN:-false}" = true ]; then
    # if domain passed by arg we just return it
    getDomain 'Enter a domain name' 'Enter a Domain Name'
  else
    # update the main domain with a selection
    getMultiDomain
  fi
}

# set the container user
function setContainerUser() {
  # ask if a new User ID should be set if one is set
  if [ -n "${VDM_PUID}" ] && [[ "${VDM_PUID}" =~ ^[0-9]+$ ]] && \
    getInputYesNo "The user ID in ${PROGRAM_NAME} memory is ${VDM_PUID}, would you like to change this user ID?" \
    "Set User ID" 8 112 "defaultno"; then
    # always first reset
    unset VDM_PUID
  fi
  # give little notice
  # showNotice "To get the ID of a user in a container:\n\n$ docker exec -it container_name /bin/bash\n$ id -u www-data"
  # we first get the container user ID
  while [ -z "${VDM_PUID}" ] || [ ${#VDM_PUID} -le 1 ] || ! [[ "${VDM_PUID}" =~ ^[0-9]+$ ]]; do
    VDM_PUID=$(getInput "Enter user ID for the ${VDM_CONTAINER_TYPE^} container. Use default:${1:-1000} if you don't know.\n[add only a number]" \
      "${1:-1000}" 'Enter User ID') || return $?
    # check if we have success
    if [ ${#VDM_PUID} -le 1 ] || ! [[ "${VDM_PUID}" =~ ^[0-9]+$ ]]; then
      showError "You must enter a user ID like: ${1:-1000} (only the number)"
    fi
  done

  # ask if a new Group ID should be set if one is set
  if [ -n "${VDM_PGID}" ] && [[ "${VDM_PGID}" =~ ^[0-9]+$ ]] && \
    getInputYesNo "The user-group ID in ${PROGRAM_NAME} memory is ${VDM_PGID}, would you like to change this user-group ID?" \
    "Set User-Group ID" 8 112 "defaultno"; then
    # always first reset
    unset VDM_PGID
  fi
  # give little notice
  # showNotice "To get the ID of a user-group in a container:\n\n$ docker exec -it container_name /bin/bash\n$ id -u www-data"
  # we get the container user-group ID
  while [ -z "${VDM_PGID}" ] || [ ${#VDM_PGID} -le 1 ] || ! [[ "${VDM_PGID}" =~ ^[0-9]+$ ]]; do
    VDM_PGID=$(getInput "Enter user-group ID for the ${VDM_CONTAINER_TYPE^} container. Use default:${1:-1000} if you don't know.\n[add only a number]" \
      "${1:-1000}" 'Enter User Group ID') || return $?
    # check if we have success
    if [ ${#VDM_PGID} -le 1 ] || ! [[ "${VDM_PGID}" =~ ^[0-9]+$ ]]; then
      showError "You must enter a user-group ID like: ${1:-1000} (only the number)"
    fi
  done
  # make available
  export VDM_PUID
  export VDM_PGID
}

# Set the program mode
function setMode() {
  # Local variable to store the mode
  local mode="${1:-basic}"
  # Local variable to store the VDM_EXPERT_MODE value
  local vdm_expert_mode="false"

  # Set the VDM_EXPERT_MODE value based on the mode
  case "$mode" in
    basic)
      vdm_expert_mode="false"
      ;;
    expert)
      vdm_expert_mode="true"
      ;;
    *)
      echo "Error: Unsupported mode. Use 'basic' or 'expert'."
      return 1
      ;;
  esac

  # Set persistent
  setUniqueEnvVariable "VDM_EXPERT_MODE=${vdm_expert_mode}" || return $?

  # Make global
  export VDM_EXPERT_MODE="$vdm_expert_mode"
}

# set the domain
function setDomain() {
  # allow multi domain setup
  if allowMultiDomains; then
    # select a domain name
    getMainDomain
  else
    # set the main domain if not set
    setMainDomain
  fi
}

# set the main domain
function setMainDomain() {
  # set the main domain if not set
  getDomain || return $?
  # add this value if not set variable
  setUniqueEnvVariable "VDM_DOMAIN=\"${VDM_DOMAIN}\""
}

# set the sub domain
function setSubDomain() {
  # make sure it has not been used before,
  # also make sure its not a port or a ....db
  while [ ${#VDM_SUBDOMAIN} -le 1 ] || [[ "${VDM_SUBDOMAIN}" =~ [^a-zA-Z] ]] ||
    [ -d "${VDM_REPO_PATH}/${3:-$VDM_CONTAINER_TYPE}/available/${VDM_SUBDOMAIN}.${VDM_DOMAIN}" ] ||
    [ -d "${VDM_REPO_PATH}/${3:-$VDM_CONTAINER_TYPE}/available/${VDM_SUBDOMAIN%db}.${VDM_DOMAIN}" ] ||
    [ "${VDM_SUBDOMAIN}" = "${2}" ]; do
    # get the value
    VDM_SUBDOMAIN=$(getInput "Enter sub-domain used for this ${VDM_CONTAINER_TYPE^} container.\n[Text with no spaces that is only alphabetical]" \
      "${1}" 'Enter Sub-Domain') || return $?
    # keep asking if empty or does exist
    if [ ${#VDM_SUBDOMAIN} -ge 1 ] && [ -d "${VDM_REPO_PATH}/${3:-$VDM_CONTAINER_TYPE}/available/${VDM_SUBDOMAIN}.${VDM_DOMAIN}" ] ||
      [ -d "${VDM_REPO_PATH}/${3:-$VDM_CONTAINER_TYPE}/available/${VDM_SUBDOMAIN%db}.${VDM_DOMAIN}" ]; then
      showError "The sub-domain:${VDM_SUBDOMAIN} is already used. Select another"
    elif [[ "${VDM_SUBDOMAIN}" =~ [^a-zA-Z] ]]; then
      showError "You must enter a sub-domain that is only alphabetical!"
    elif [ ${#VDM_SUBDOMAIN} -le 1 ]; then
      showError "You must enter a sub-domain!"
    fi
  done
  # make sure it is available
  export VDM_SUBDOMAIN
}

# to set a global multiple domains file and values
function setMultiDomains() {
  # set some locals
  local domain_name
  local list_domains
  local question
  # allow multi domain setup
  if allowMultiDomains; then
    # get the list of domains
    list_domains=$(getListDomains "\n")
    # the question based on current state
    [ -f "${VDM_SRC_PATH}/.domains" ] && question="Would you like to add another domain to ${PROGRAM_NAME}?\nThese Domains already set:\n${list_domains}" ||
      question="Would you like to add a domain to ${PROGRAM_NAME}?"
    # get the key if not set
    while (whiptail --yesno "${question}" --scrolltext --defaultno \
      --title "Add Domain" --backtitle "${BACK_TITLE}" 20 112); do
      # now clear the main domain each time
      unset VDM_DOMAIN
      # we must let them enter the new domain name
      getDomain 'Enter a domain name' 'Enter a Domain Name'
      # add for next time
      saveMultiDomain "${VDM_DOMAIN}"
      # get the list of domains
      list_domains=$(getListDomains "\n")
      # update the question
      question="Would you like to add another domain to ${PROGRAM_NAME}?\nThese Domains already set:\n${list_domains}"
    done
  fi
}

# set the multi domain switch
function setMultiDomainSwitch() {
  # Allow multiple domains
  if [ "${VDM_MULTI_DOMAIN:-not}" = 'not' ]; then
    # explain the pros and cons...
    showNotice "Next you should make the selection of using a single or multiple domain setup.\n\n\
      With multiple domain setups you will need to select a main domain each time you setup a new container.\n\
      With a single domain setup you setup the main domain once, and then only need setup the subdomains\n\
      with each new container."
    # check the security switch
    if (whiptail --yesno "Would you like to use a multiple domains setup?" \
      --defaultno --title "Allow Multi Domains" --backtitle "${BACK_TITLE}" 8 112); then
      # we set the secure switch
      VDM_MULTI_DOMAIN=true
    else
      VDM_MULTI_DOMAIN=false
    fi
  fi
  # add this value if not set variable
  setEnvVariable "VDM_MULTI_DOMAIN=${VDM_MULTI_DOMAIN}" || return $?
  # make sure it is available
  export VDM_MULTI_DOMAIN
}

# set the unique key
function setUniqueKey() {
  # get the key if not set
  while [ ${#VDM_KEY} -le 1 ] || [ -d "${VDM_PROJECT_PATH}/${VDM_KEY}" ] || [[ "${VDM_KEY}" =~ [^a-zA-Z] ]]; do
    # get the value
    VDM_KEY=$(getInput "${1:-Enter key used for container naming and name of the persistent volume folder.}\n[Text with no spaces that is only alphabetical]" \
      '' 'Enter Key') || return $?
    # keep asking if empty or does exist
    if [ ${#VDM_KEY} -ge 1 ] && [ -d "${VDM_PROJECT_PATH}/${VDM_KEY}" ]; then
      showError "The key:${VDM_KEY} is already used. Select another"
    elif [[ "${VDM_KEY}" =~ [^a-zA-Z] ]]; then
      showError "You must enter a key with no spaces that is only alphabetical!"
    elif [ ${#VDM_KEY} -le 1 ]; then
      showError "You must enter a key!"
    fi
  done
  # make sure it is available
  export VDM_KEY
}

# set the Joomla website details
function setJoomlaWebsiteDetails() {
  # ask if we should add auto deployment
  if getInputYesNo "Would you like to enable website auto deploy for ${VDM_CONTAINER_TYPE,}:${VDM_JV}" \
    "Enable Auto deploy" 8 112; then

    # ask for website name
    setJoomlaSiteName || return $?

    # ask for username
    setJoomlaUsername || return $?

    # ask for user
    setJoomlaUser || return $?

    # ask for email
    setJoomlaEmail || return $?

    # ask for username password
    setJoomlaPassword || return $?

    # ask for extension URLs
    setJoomlaExtensionUrls || return $?

    # ask for the commands if we are targeting the correct set of images
    if [[ "${VDM_J_REPO}" == "octoleo/joomengine" ]]; then
      setJoomlaCommands || return $?
    fi
  fi
}

# set the website name
function setJoomlaSiteName() {
  # get the key if not set
  while [ ${#VDM_J_SITE_NAME} -le 2 ]; do
    # get the value
    VDM_J_SITE_NAME=$(getInput "Enter a Joomla website name." \
      'Joomla! CMS' 'Enter Site Name') || return $?
    # keep asking if empty
    if [ ${#VDM_J_SITE_NAME} -le 2 ]; then
      showError "You must enter a site name longer than 2 characters!"
    fi
  done
  # make sure it is available
  export VDM_J_SITE_NAME
}

# set the username
function setJoomlaUsername() {
  # get the key if not set
  while [ ${#VDM_J_USERNAME} -le 1 ] || [[ "${VDM_J_USERNAME}" =~ [^a-zA-Z] ]]; do
    # get the value
    VDM_J_USERNAME=$(getInput "Enter a Joomla username.\n[Text with no spaces that is only alphabetical]" \
      'user' 'Enter Username') || return $?
    # keep asking if empty
    if [[ "${VDM_J_USERNAME}" =~ [^a-zA-Z] ]]; then
      showError "You must enter a username with no spaces that is only alphabetical!"
    elif [ ${#VDM_J_USERNAME} -le 1 ]; then
      showError "You must enter a username!"
    fi
  done
  # make sure it is available
  export VDM_J_USERNAME
}

# set the user
function setJoomlaUser() {
  # get the key if not set
  while [ ${#VDM_J_USER} -le 2 ]; do
    # get the value
    VDM_J_USER=$(getInput "Enter a Joomla user." \
      'John Doe' 'Enter User Name') || return $?
    # keep asking if empty
    if [ ${#VDM_J_USER} -le 2 ]; then
      showError "You must enter a user!"
    fi
  done
  # make sure it is available
  export VDM_J_USER
}

# set the email
function setJoomlaEmail() {
  # Email regex for basic validation
  local email_regex="^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$"

  # Keep prompting until a valid email is provided
  while [[ ! "${VDM_J_EMAIL}" =~ $email_regex ]]; do
    # Get the email
    VDM_J_EMAIL=$(getInput "Enter a Joomla email address." \
      'admin@example.org' 'Enter Email') || return $?

    # Check if the input matches the basic email regex pattern
    if [[ ! "${VDM_J_EMAIL}" =~ $email_regex ]]; then
      showError "You must enter a valid email address!"
    fi
  done

  # Export the variable to make it available for child processes
  export VDM_J_EMAIL
}

# set the username
function setJoomlaPassword() {
  # get the key if not set
  while [ ${#VDM_J_PASSWORD} -le 12 ]; do
    # get the value
    VDM_J_PASSWORD=$(getInput "Enter Joomla User Password" \
      'joomla-17082005' 'Enter Joomla User Password') || return $?
    # keep asking if empty
    if [ ${#VDM_J_PASSWORD} -le 12 ]; then
      showError "You must enter a password with more than 11 characters!"
    fi
  done
  # make sure it is available
  export VDM_J_PASSWORD
}

# This function asks for Joomla extension ZIP URLs using whiptail, validates them,
# and concatenates them into a single environment variable.
function setJoomlaExtensionUrls() {
    local urls=()
    local input=""
    local prompt_message="Enter Joomla Extension ZIP URL (leave empty to for none):"
    local title="Enter Joomla Extension Installation URL"
    unset VDM_J_EXTENSIONS_URLS

    # Loop to collect URLs until an empty string or cancellation
    while true; do
        input=$(getInput "$prompt_message" "" "$title") || return $?

        # Break loop if input is empty
        if [[ -z "$input" ]]; then
            break
        fi

        # Validate URL format
       if [[ "$input" =~ ^http(s)?://[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}(/.*)?$ ]]; then
            urls+=("$input")
        else
            showNotice "Invalid URL. Please enter a valid ZIP URL (must be a .zip file)." 10
        fi
    done

    # Join URLs with semicolons
    if [ ${#urls[@]} -gt 0 ]; then
        VDM_J_EXTENSIONS_URLS=$(IFS=';'; echo "${urls[*]}")
        export VDM_J_EXTENSIONS_URLS
    fi
}

# This function asks for Joomla commands using whiptail, validates them,
# and concatenates them into a single environment variable.
function setJoomlaCommands() {
    local j_commands=()
    local input=""
    local prompt_message="Enter Joomla cli command passed to cli/joomla.php script (leave empty for none):"
    local title="Enter a Joomla command"
    unset VDM_J_CLI_COMMANDS

    # Loop to collect commands until an empty string or cancellation
    while true; do
        input=$(getInput "$prompt_message" "" "$title") || return $?

        # Break loop if input is empty
        if [[ -z "$input" ]]; then
            break
        fi

        # Validate command format
       if joomlaValidateCliCommand "$input"; then
            j_commands+=("$input")
        else
            showNotice "Invalid Joomla CLI command. Please enter a valid joomla cli command." 10
        fi
    done

    # Join Commands with semicolons
    if [ ${#j_commands[@]} -gt 0 ]; then
        VDM_J_CLI_COMMANDS=$(IFS=';'; echo "${j_commands[*]}")
        export VDM_J_CLI_COMMANDS
    fi
}

# Validate Joomla CLI command (ENV + Docker safe)
function joomlaValidateCliCommand() {

	local cmd="$1"
	local len

	# Must not be empty
	[[ -n "$cmd" ]] || return 1

	# Length check
	len=${#cmd}
	(( len >= 5 && len <= 4096 )) || return 1

	# Must be single-line (no CR/LF)
	[[ "$cmd" != *$'\n'* ]] || return 1
	[[ "$cmd" != *$'\r'* ]] || return 1

	# Only allow printable ASCII (space to tilde)
	# This excludes control chars automatically
	[[ "$cmd" =~ ^[[:print:]]+$ ]] || return 1

	# Block shell command substitution
	[[ "$cmd" != *'`'* && "$cmd" != *';'* ]] || return 1
	# shellcheck disable=SC2016
	[[ "$cmd" != *'$('* ]] || return 1

	return 0
}

# set the number of containers to build
function setNumberContainers() {
  local valid=0
  local count
  while [ "$valid" -eq 0 ]; do
    # get the value
    VDM_NUMBER_CONTAINERS=$(getInput "Enter the number of containers you would like to deploy.\n[Just a number!]" \
      10 'Enter Number') || return $?
    # check that the number is above 1 and below 100
    if ! [[ $VDM_NUMBER_CONTAINERS =~ ^[0-9]{1,2}$ ]]; then
      showError "You must enter a number from 2 to 99!"
    else
      count=$((10#$VDM_NUMBER_CONTAINERS))
      if [ "$count" -le 1 ]; then
        showError "The number (${VDM_NUMBER_CONTAINERS}) must be above 1"
      else
        VDM_NUMBER_CONTAINERS="$count"
        valid=1
      fi
    fi
  done
  # make sure it is available
  export VDM_NUMBER_CONTAINERS
}

# set the Environment key
function setEnvironmentKey() {
  # get the env key if not set
  while [ ${#VDM_ENV_KEY} -le 1 ] || [[ "${VDM_ENV_KEY}" =~ [^a-zA-Z] ]]; do
    # get the value
    VDM_ENV_KEY=$(getInput "Enter environment key used to load the container environment variables.\n[Text with no spaces that is only alphabetical UPPERCASE]" \
      "${VDM_KEY^^}" 'Enter ENV Key') || return $?
    # keep asking if empty or does exist
    if [ ${#VDM_ENV_KEY} -le 1 ]; then
      showError "You must enter an environment key!"
    elif [[ "${VDM_ENV_KEY}" =~ [^a-zA-Z] ]]; then
      showError "You must enter an environment key with no spaces that is only alphabetical!"
    fi
  done
  # make sure it is available
  export VDM_ENV_KEY="${VDM_ENV_KEY^^}"
}

# set the update of host files
function setUpdateHostFile() {
  # check if we have secure switch set
  if [ "${VDM_UPDATE_HOST:-not}" = 'not' ]; then
    # check the security switch
    if (whiptail --yesno "Would you like to update your host file with each new domain you add?" \
      --defaultno --title "Update /etc/hosts" --backtitle "${BACK_TITLE}" 8 112); then
      # we set the secure switch
      VDM_UPDATE_HOST=true
    else
      VDM_UPDATE_HOST=false
    fi
  fi
  # add this value since its not set variable
  setEnvVariable "VDM_UPDATE_HOST=${VDM_UPDATE_HOST}" || return $?
  # make sure it is available
  export VDM_UPDATE_HOST
}

# set the image source values
function setImageSource() {
  # some local values
  local vdm_image_source
  local vdm_tag_url
  # get the Joomla version if not set
  while [ -z "${VDM_J_REPO}" ] || [ ${#VDM_J_REPO} -le 3 ]; do
    # get the image source
    vdm_image_source=$(getImageSource) || return $?
    # build the source key (string before the first | )
    VDM_J_REPO="${vdm_image_source%%|*}"
    # set the source entry-point (url after the last ; )
    VDM_ENTRY_REPO="${vdm_image_source##*;}"
    # remove the J_REPO (remove everything before the first | )
    vdm_image_source="${vdm_image_source##*|}"
    # set the source entry-point (string before the first ; )
    vdm_tag_url="${vdm_image_source%%;*}"
    # keep asking
    [ ${#VDM_J_REPO} -le 3 ] && {
      showError "Seems like the source selected is not correctly configured, please select another."
    }
    # make sure the source is set
    [[ "${VDM_ENTRY_REPO}" == *'docker-entrypoint.sh' ]] || {
      VDM_J_REPO=''
      showError "Seems like the source selected is not correctly configured, please select another."
    }
  done
  # get the Joomla version if not set
  while [ ${#VDM_JV} -le 1 ]; do
    # get the value
    VDM_JV=$(getInput "Enter Joomla version tag for this container.\n[See available tags here ${vdm_tag_url}]" 'latest' 'Enter Version Tag') || return $?
    # keep asking
    [ ${#VDM_JV} -ge 1 ] || {
      showError "You must enter a version tag. See available tags here ${vdm_tag_url}"
    }
  done
  # make the value available globally
  export VDM_ENTRY_REPO
  export VDM_J_REPO
  export VDM_JV
}

# check version
function isVersionAbove() {
  local tag="$1" target_version="$2" tag_major tag_minor target_major target_minor
  local numeric_version='^([0-9]{1,9})(\.([0-9]{1,9}))?(\.[0-9]{1,9})?$'
  local image_version='^([0-9]{1,9})(\.([0-9]{1,9}))?(\.[0-9]{1,9})?(-[a-zA-Z0-9_.-]+)?$'
  # Validate digits and their size before arithmetic: Bash otherwise evaluates
  # variable names and array subscripts supplied inside a malicious image tag.
  [[ "$target_version" =~ $numeric_version ]] || return 1
  target_major=$((10#${BASH_REMATCH[1]}))
  target_minor=$((10#${BASH_REMATCH[3]:-0}))
  [[ "$tag" =~ ^latest(-[a-zA-Z0-9_.-]+)?$ ]] && return 0
  [[ "$tag" =~ $image_version ]] || return 1
  tag_major=$((10#${BASH_REMATCH[1]}))
  tag_minor=$((10#${BASH_REMATCH[3]:-0}))
  (( tag_major > target_major || (tag_major == target_major && tag_minor >= target_minor) ))
}

# set persistence volumes
function setPersistence() {
  # ask the question
  if getInputYesNo "Would you like to enable persistence on this $1." \
    "Persist Volume" 8 112; then
    # yes persistence
    return 0
  fi
  # no persistence
  return 1
}

# Optional customization contract: 0 configured, 1 explicitly declined,
# >=2 failed or cancelled. Once selected, an ordinary command failure (1)
# must never be confused with declining the customization.
function setPHPSettings() {
  local customization_status
  # ask the question
  if getInputYesNo "Would you like to set some PHP overrides for the Joomla container.\n\nTo make these changes we need sudo privileges." \
    "PHP.ini values" 9 112; then
    if configurePHPSettings; then
      return 0
    else
      customization_status=$?
      [ "$customization_status" -gt 1 ] || customization_status=2
      return "$customization_status"
    fi
  else
    return $?
  fi
}

function configurePHPSettings() {
    local default_error_reporting edit_status
    # max_execution_time
    VDM_max_execution_time=$(getInputNow "Enter max execution time" \
        "${VDM_max_execution_time:-124}" 'max_execution_time') || return $?
    # remember this for next time
    setUniqueEnvVariable "VDM_max_execution_time=${VDM_max_execution_time}" || return $?

    # max_input_time
    VDM_max_input_time=$(getInputNow "Enter max input time" \
        "${VDM_max_input_time:-1500}" 'max_input_time') || return $?
    # remember this for next time
    setUniqueEnvVariable "VDM_max_input_time=${VDM_max_input_time}" || return $?

    # max_input_vars
    VDM_max_input_vars=$(getInputNow "Enter max_input_vars" \
        "${VDM_max_input_vars:-3000}" 'max_input_vars') || return $?
    # remember this for next time
    setUniqueEnvVariable "VDM_max_input_vars=${VDM_max_input_vars}" || return $?

    # error_reporting
    default_error_reporting="E_ALL & ~E_DEPRECATED & ~E_STRICT"
    VDM_error_reporting=$(getInputNow "Enter error reporting" \
        "${VDM_error_reporting:-$default_error_reporting}" 'error_reporting') || return $?
    # remember this for next time
    setUniqueEnvVariable "VDM_error_reporting=\"${VDM_error_reporting}\"" || return $?

    # upload_max_filesize
    VDM_upload_max_filesize=$(getInputNow "Enter upload max filesize" \
        "${VDM_upload_max_filesize:-256M}" 'upload_max_filesize') || return $?
    # remember this for next time
    setUniqueEnvVariable "VDM_upload_max_filesize=\"${VDM_upload_max_filesize}\"" || return $?

    # post_max_size
    VDM_post_max_size=$(getInputNow "Enter post max size" \
        "${VDM_post_max_size:-256M}" 'post_max_size') || return $?
    # remember this for next time
    setUniqueEnvVariable "VDM_post_max_size=\"${VDM_post_max_size}\"" || return $?

    # memory_limit
    VDM_memory_limit=$(getInputNow "Enter memory limit" \
        "${VDM_memory_limit:-256M}" 'memory_limit') || return $?
    # remember this for next time
    setUniqueEnvVariable "VDM_memory_limit=\"${VDM_memory_limit}\"" || return $?

    # make sure the directory exist
    mkdir -p "${VDM_PROJECT_PATH}/${VDM_PHP_PROJECT_PATH}" || return $?

    # push all these values to the php.ini file
    {
      echo "max_execution_time = ${VDM_max_execution_time}"
      echo "max_input_time = ${VDM_max_input_time}"
      echo "max_input_vars = ${VDM_max_input_vars}"
      echo "error_reporting = ${VDM_error_reporting}"
      echo "upload_max_filesize = ${VDM_upload_max_filesize}"
      echo "post_max_size = ${VDM_post_max_size}"
      echo "memory_limit = ${VDM_memory_limit}"
    } > "${VDM_PROJECT_PATH}/${VDM_PHP_PROJECT_PATH}/php.ini" || return 1

    # allow custom edit
    if isExpert; then
      if getInputYesNo "Would you like to set some more custom PHP overrides for this Joomla container" \
        "Edit PHP.ini" 8 112 "defaultno"; then
        # give little heads-up
        showNotice "${USER^}, to save the changes you've made or to just close the file again press:\n\n[ctrl+x] with nano on ubuntu." 13
        # lets open the file with nano for now
        sudo "${EDITOR:-nano}" "${VDM_PROJECT_PATH}/${VDM_PHP_PROJECT_PATH}/php.ini" || return $?
      else
        edit_status=$?
        [ "$edit_status" -eq 1 ] || return "$edit_status"
      fi
    fi

    # set the ownership
    if [ -n "${VDM_PUID}" ] && [ -n "${VDM_PGID}" ]; then
      sudo chown "${VDM_PUID}":"${VDM_PGID}" "${VDM_PROJECT_PATH}/${VDM_PHP_PROJECT_PATH}/php.ini" || return $?
    else
      sudo chown www-data:www-data "${VDM_PROJECT_PATH}/${VDM_PHP_PROJECT_PATH}/php.ini" || return $?
    fi
    # make sure the permission are good
    sudo chmod 600 "${VDM_PROJECT_PATH}/${VDM_PHP_PROJECT_PATH}/php.ini" || return $?

    # yes load php.ini volume to the container
    return 0
}

# set the docker entrypoint
function setDockerEntrypoint() {
  local customization_status
  # ask the question
  if getInputYesNo "Would you like to customize the entrypoint script for this Joomla container" \
    "entrypoint.sh values" 8 112 "defaultno"; then
    if configureDockerEntrypoint; then
      return 0
    else
      customization_status=$?
      [ "$customization_status" -gt 1 ] || customization_status=2
      return "$customization_status"
    fi
  else
    return $?
  fi
}

function configureDockerEntrypoint() {
    local entrypoint_dir="${VDM_PROJECT_PATH}/${VDM_ENTRY_PROJECT_PATH}" temporary customization_status
    # make sure the directory exist
    mkdir -p "$entrypoint_dir" || return $?
    temporary=$(mktemp "${entrypoint_dir}/entrypoint.sh.tmp.XXXXXX") || return $?
    # download entrypoint.sh file to the project folder
    if sudo curl --fail -L "${VDM_ENTRY_REPO}" -o "$temporary" 2>/dev/null; then
      # give little heads-up
      showNotice "${USER^}, to save the changes you've made or to just close the file again press:\n\n[ctrl+x] with nano on ubuntu." 13
      # lets open the file with nano for now
      if sudo "${EDITOR:-nano}" "$temporary" &&
        sudo chown 0:0 "$temporary" && sudo chmod 700 "$temporary" &&
        sudo mv -f "$temporary" "${entrypoint_dir}/entrypoint.sh"; then
        return 0
      else
        customization_status=$?
        sudo rm -f "$temporary"
        return "$customization_status"
      fi
    else
      customization_status=$?
      sudo rm -f "$temporary"
      # show the error
      showError "The entrypoint.sh could not be set."
      return "$customization_status"
    fi
}

# Set the secure Cloudflare state
function setSecureCloudflareState() {
	# Determine caller
	local caller="${1:-generic}"
	local question=""
	local title="Cloudflare"

	# Build caller-specific question
	if [[ "$caller" == "traefik" ]]; then
		question="Will any of the domains hosted on this server be proxied through Cloudflare?\n\nCloudflare's proxy layer requires special handling in Traefik."
	elif [[ "$caller" == "joomla" ]]; then
		question="Is the domain for this Joomla instance proxied through Cloudflare?\n\nCloudflare's proxy layer requires special handling for this container."
	else
		# Fallback if future tools call it
		question="Is the domains involved in this setup proxied through Cloudflare?\n\nCloudflare's proxy layer requires special handling."
	fi

	# Ask the user
	if getInputYesNo "$question" "$title" 10 112 "defaultno"; then
		VDM_SECURE_CLOUDFLARE=true
	else
		VDM_SECURE_CLOUDFLARE=false
	fi

	export VDM_SECURE_CLOUDFLARE
}

# set the secure state
function setSecureState() {
  if [ "${VDM_SECURE:-not}" = 'not' ]; then
    # check the security switch
    if getInputYesNo "Would you like to use Letsencrypt auto setup for your containers [ONLY for server with public static IP]" \
      "Letsencrypt" 8 112 "defaultno"; then
      # we set the secure switch
      VDM_SECURE=true
    else
      VDM_SECURE=false
    fi
  fi
  # add this value if not set variable
  setEnvVariable "VDM_SECURE=${VDM_SECURE}" || return $?
  # make sure it is available
  export VDM_SECURE
}

# Create Docker networks if they do not exist (IPv6 auto-detect)
function setNetworks() {

	# Default network names and subnets
	local traefik_gateway="${VDM_TRAEFIK_GATEWAY:-traefik_webgateway}"
	local traefik_subnet="${VDM_TRAEFIK_SUBNET:-172.22.0.0/24}"
	local traefik_subnet6="${VDM_TRAEFIK_SUBNET6:-fd00:22::/64}"

	local openssh_gateway="${VDM_OPENSSH_GATEWAY:-openssh_gateway}"
	local openssh_subnet="${VDM_OPENSSH_SUBNET:-172.23.0.0/24}"
	local openssh_subnet6="${VDM_OPENSSH_SUBNET6:-fd00:23::/64}"

	# Ensure Docker is reachable
	if ! docker info >/dev/null 2>&1; then
		echo "ERROR: Docker daemon not running or permission denied." >&2
		return 1
	fi

	# Detect IPv6 support
	local ipv6_enabled=false
	if docker info 2>/dev/null | grep -qE '^ *IPv6: *true'; then
		ipv6_enabled=true
	fi

	# -----------------------
	# Traefik network
	# -----------------------
	if ! docker network inspect "${traefik_gateway}" >/dev/null 2>&1; then
		echo "Creating Docker network: ${traefik_gateway}"

		if [[ "$ipv6_enabled" == true ]]; then
			docker network create \
				--driver bridge \
				--ipv6 \
				--subnet "$traefik_subnet" \
				--subnet "$traefik_subnet6" \
				"${traefik_gateway}" || return $?
		else
			docker network create \
				--driver bridge \
				--subnet "$traefik_subnet" \
				"${traefik_gateway}" || return $?
		fi
	fi

	# -----------------------
	# OpenSSH network
	# -----------------------
	if ! docker network inspect "${openssh_gateway}" >/dev/null 2>&1; then
		echo "Creating Docker network: ${openssh_gateway}"

		if [[ "$ipv6_enabled" == true ]]; then
			docker network create \
				--driver bridge \
				--ipv6 \
				--subnet "$openssh_subnet" \
				--subnet "$openssh_subnet6" \
				"${openssh_gateway}" || return $?
		else
			docker network create \
				--driver bridge \
				--subnet "$openssh_subnet" \
				"${openssh_gateway}" || return $?
		fi
	fi
}

# Serialize caller-supplied assignment data for Compose, without interpolation.
# Callers pass KEY="raw value"; those outer quotes are syntax, internal quotes
# and backslashes are user data. Never evaluate the assignment as shell code.
function formatEnvAssignment() {
  local line="$1" key="${1%%=*}" value="${1#*=}" quoted=false
  [[ "$line" == *=* && "$key" =~ ^VDM_[a-zA-Z0-9_]+$ ]] || return 12
  [[ "$line" != *$'\n'* && "$line" != *$'\r'* ]] || return 12
  if [[ "$value" == \"*\" || "$value" == \'*\' ]]; then
    value="${value:1:${#value}-2}"
    quoted=true
  fi
  if ! "$quoted" && [[ "$value" =~ ^[a-zA-Z0-9_.:/+-]*$ ]]; then
    printf '%s=%s\n' "$key" "$value"
  else
    value="${value//\\/\\\\}"
    value="${value//\"/\\\"}"
    value="${value//\$/\\\$}"
    value="${value//$'\t'/\\t}"
    printf '%s="%s"\n' "$key" "$value"
  fi
}

# Decode one dotenv value into the named caller variable; no source or eval.
function decodeEnvValue() {
  local decode_text="$1" decode_target="$2" decode_quote decode_char decode_next
  local decode_result='' decode_rest decode_i decode_closed=false
  decode_text="${decode_text#"${decode_text%%[!$' \t']*}"}"
  decode_quote="${decode_text:0:1}"
  if [[ "$decode_quote" != '"' && "$decode_quote" != "'" ]]; then
    decode_result="${decode_text%%' #'*}"
    decode_result="${decode_result%"${decode_result##*[!$' \t']}"}"
  else
    for ((decode_i=1; decode_i<${#decode_text}; decode_i++)); do
      decode_char="${decode_text:decode_i:1}"
      if [[ "$decode_char" == "$decode_quote" ]]; then
        decode_rest="${decode_text:decode_i+1}"
        decode_rest="${decode_rest#"${decode_rest%%[!$' \t']*}"}"
        [[ -z "$decode_rest" || "$decode_rest" == \#* ]] || return 12
        decode_closed=true
        break
      elif [[ "$decode_char" == "\\" ]]; then
        decode_next="${decode_text:decode_i+1:1}"
        if [[ "$decode_next" == "$decode_quote" ]]; then
          decode_char="$decode_next"
          decode_i=$((decode_i+1))
        elif [[ "$decode_quote" == '"' ]]; then
          case "$decode_next" in
            "\\"|'$'|'`') decode_char="$decode_next"; decode_i=$((decode_i+1)) ;;
            n) decode_char=$'\n'; decode_i=$((decode_i+1)) ;;
            r) decode_char=$'\r'; decode_i=$((decode_i+1)) ;;
            t) decode_char=$'\t'; decode_i=$((decode_i+1)) ;;
          esac
        fi
      fi
      decode_result+="$decode_char"
    done
    "$decode_closed" || return 12
  fi
  printf -v "$decode_target" '%s' "$decode_result"
}

# Configuration files contain data, never executable shell. Validate the whole
# file before assigning anything so malformed files cannot partly alter state.
function loadEnvFile() {
  local env_file="$1" env_line env_key env_value env_i
  local env_keys=() env_values=()
  [ -f "$env_file" ] && [ -r "$env_file" ] || return 12
  while IFS= read -r env_line || [ -n "$env_line" ]; do
    env_line="${env_line%$'\r'}"
    [[ "$env_line" =~ ^[[:space:]]*(#.*)?$ ]] && continue
    if [[ "$env_line" =~ ^[[:space:]]*(export[[:space:]]+)?(VDM_[a-zA-Z0-9_]+)[[:space:]]*=[[:space:]]*(.*)$ ]]; then
      env_key="${BASH_REMATCH[2]}"
      decodeEnvValue "${BASH_REMATCH[3]}" env_value || return 12
      case "$env_key" in
        VDM_FORCE|VDM_SECURE|VDM_SECURE_CLOUDFLARE|VDM_MULTI_DOMAIN|VDM_UPDATE_HOST|VDM_EXPERT_MODE|VDM_ARG_DOMAIN|VDM_FIRST_RUN|VDM_SRC_NAMED_VOLUMES|VDM_SRC_MAILCATCHER)
          [[ "$env_value" == true || "$env_value" == false ]] || return 12 ;;
      esac
      env_keys+=("$env_key")
      env_values+=("$env_value")
    else
      printf 'Invalid configuration in %s. Only VDM_ assignments are supported.\n' "$env_file" >&2
      return 12
    fi
  done < "$env_file"
  for ((env_i=0; env_i<${#env_keys[@]}; env_i++)); do
    printf -v "${env_keys[env_i]}" '%s' "${env_values[env_i]}" || return 12
  done
}

# Keep secrets private from creation, preserve existing keys, and never report
# a failed write as success. Replacement uses an adjacent temporary file.
function writeEnvVariable() {
  local env_file="$1" assignment="$2" replace="${3:-false}" line key temporary
  line=$(formatEnvAssignment "$assignment") || return 12
  key="${line%%=*}"
  if [ ! -f "$env_file" ]; then
    getInputYesNo "Can we create the ${env_file} file" "Environment Variable File" 8 112 || return 12
    mkdir -p "${env_file%/*}" || return 12
    (umask 077; set -C; printf '%s\n' "$line" > "$env_file") || return 12
    chmod 600 "$env_file" || return 12
    return 0
  fi
  chmod 600 "$env_file" || return 12
  if ! "$replace"; then
    grep -Eq "^[[:space:]]*(export[[:space:]]+)?${key}[[:space:]]*=" "$env_file" && return 0
    printf '%s\n' "$line" >> "$env_file" || return 12
  else
    temporary=$(mktemp "${env_file}.tmp.XXXXXX") || return 12
    if ! awk -v key="$key" '$0 !~ ("^[[:space:]]*(export[[:space:]]+)?" key "[[:space:]]*=")' "$env_file" > "$temporary" ||
      ! printf '%s\n' "$line" >> "$temporary" || ! chmod 600 "$temporary" ||
      ! mv -f "$temporary" "$env_file"; then
      rm -f "$temporary"
      return 12
    fi
  fi
  return 0
}

function setUniqueEnvVariable() {
  writeEnvVariable "${VDM_SRC_PATH}/.env" "$1" true
}

function setEnvVariable() {
  writeEnvVariable "${VDM_SRC_PATH}/.env" "$1"
}

function setContainerEnvVariable() {
  [[ "${VDM_CONTAINER_TYPE:-}" =~ ^[a-zA-Z0-9_-]+$ ]] || return 12
  writeEnvVariable "${VDM_REPO_PATH}/${VDM_CONTAINER_TYPE}/.env" "$1"
}

# get the env file to use with a container's docker-compose.yml
# $1: container type (joomla, openssh, ...)
# $2: container name (sub.domain.tld)
# $3 (optional): state directory to look in (enabled or available), default enabled
# A per-container .env (available/<container>/.env, also reachable through the
# enabled/<container> symlink) wins over the shared <type>/.env file.
# Prints the path, or nothing when neither file exists.
function getContainerEnvFile() {
  local container_type="${1:-$VDM_CONTAINER_TYPE}"
  local container="${2:-}"
  local state="${3:-enabled}"
  if [ -n "${container}" ] && [ -f "${VDM_REPO_PATH}/${container_type}/${state}/${container}/.env" ]; then
    echo "${VDM_REPO_PATH}/${container_type}/${state}/${container}/.env"
  elif [ -f "${VDM_REPO_PATH}/${container_type}/.env" ]; then
    echo "${VDM_REPO_PATH}/${container_type}/.env"
  else
    echo ''
  fi
}

# check if a Directory exist and if it has sub-directories
function hasDirectories() {
  local path="${2:-$VDM_REPO_PATH}/${1:-}" directory
  [ -d "$path" ] || return 1
  for directory in "${path%/}/"* "${path%/}/".[!.]* "${path%/}/"..?*; do
    [ -d "$directory" ] && return 0
  done
  return 1
}

# lsof returns 1 with no output when nothing is listening. Diagnostics or any
# other nonzero status mean the scan failed, rather than proving ports are free.
function getPortListeners() {
  local listeners scan_status
  if [ "${OS_NUMBER:-0}" -eq 3 ]; then
    # Windows ships netstat; sudo and lsof are not Git Bash prerequisites.
    if ! listeners=$(netstat.exe -ano -p TCP 2>&1); then
      printf 'Unable to inspect ports 80 and 443: %s\n' "$listeners" >&2
      return 1
    fi
    # Emit the same nine columns consumed by ensurePortsFree's lsof parser.
    # Print no header when the selected ports have no listening sockets.
    printf '%s\n' "$listeners" | awk '
      { gsub(/\r/, "") }
      $1 == "TCP" && $4 == "LISTENING" && $2 ~ /:(80|443)$/ {
        if (!header++) print "COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME"
        print "netstat", $5, "- - TCP - - -", $2
      }'
    return 0
  fi
  if listeners=$(sudo lsof -a -nP -iTCP:80 -iTCP:443 -sTCP:LISTEN 2>&1); then
    scan_status=0
  else
    scan_status=$?
  fi
  if [ "$scan_status" -ne 0 ] && { [ "$scan_status" -ne 1 ] || [ -n "$listeners" ]; }; then
    printf 'Unable to inspect ports 80 and 443: %s\n' "$listeners" >&2
    return 1
  fi
  printf '%s' "$listeners"
}

# Ensure that no system service or process is blocking ports 80 or 443 before Traefik starts
function ensurePortsFree() {
	# Known Linux services that may bind to ports 80/443
	local web_services=("apache2" "httpd" "nginx" "lighttpd" "caddy")
	local conflict_services=()
	local port_users=""
	local message=""
	local os_label=""
	local port_output line proc_name ws svc

	# If Traefik container is running → skip everything
	if isContainerRunning 'traefik'; then
		# Traefik already has the ports → do nothing
		return 0
	fi

	# Label OS for messaging
	case "$OS_NUMBER" in
		1) os_label="Linux" ;;
		2) os_label="macOS" ;;
		3) os_label="Windows" ;;
		*) os_label="Unknown OS" ;;
	esac

	# Universal port scan (Linux, macOS, WSL, MSYS)
	port_output=$(getPortListeners) || {
		showError "Ports 80 and 443 could not be inspected. Check the port-query tools and permissions before enabling Traefik."
		return 1
	}
	port_users=$(printf '%s\n' "$port_output" | awk 'NR>1 {print $1 ":" $2 ":" $9}')

	# Nothing using ports → success
	if [ -z "$port_users" ]; then
		return 0
	fi

	# If Linux → detect systemd services we know how to stop
	if [ "$OS_NUMBER" -eq 1 ]; then
		while IFS= read -r line; do
			proc_name=$(echo "$line" | cut -d':' -f1)

			for ws in "${web_services[@]}"; do
				if [[ "$proc_name" == "$ws" ]]; then
					conflict_services+=("$ws")
				fi
			done
		done <<< "$port_users"

		# Remove duplicates
		if [ "${#conflict_services[@]}" -gt 0 ]; then
			readarray -t conflict_services < <(printf "%s\n" "${conflict_services[@]}" | sort -u)
		fi
	fi

	# Build message
	message="Traefik requires exclusive access to ports 80 and 443.\n\n"
	message+="Current port usage detected on ${os_label}:\n\n${port_users}\n\n"

	if [ "$OS_NUMBER" -eq 1 ] && [ ${#conflict_services[@]} -gt 0 ]; then
		message+="Detected known Linux web services:\n"
		for svc in "${conflict_services[@]}"; do
			message+="  • ${svc}\n"
		done
		message+="\nThese can be stopped and disabled automatically.\n"
	else
		message+="An unknown or non-Linux process is blocking these ports.\n"
		message+="Because this process cannot be managed automatically, Traefik cannot be enabled.\n"
		message+="\nPlease stop the process manually and try again.\n"
		showError "$message"
		return 1
	fi

	# Ask user to disable Linux services
	message+="\nWould you like us to stop and disable these services?"

	if getInputYesNo "$message" "Free Ports 80 & 443" 20 112 "defaultno"; then

		# Stop/disable Linux services
		for svc in "${conflict_services[@]}"; do
			if systemctl is-active --quiet "$svc"; then
				sudo systemctl stop "$svc" || return 1
			fi
			if systemctl is-enabled --quiet "$svc"; then
				sudo systemctl disable "$svc" || return 1
			fi
		done

		# Re-check
		sleep 1
		local still_used
		still_used=$(getPortListeners) || return 1

		if [ -n "$still_used" ]; then
			showError "Even after disabling services, something is still occupying ports 80/443:\n\n${still_used}\n\nTraefik cannot start."
			return 1
		fi

		showNotice "All conflicting services were disabled.\nTraefik now has exclusive access to ports 80 and 443."
		return 0

	else
		# User said NO → do not enable Traefik
		showError "Traefik cannot run unless ports 80 and 443 are free.\nOperation cancelled."
		return 1
	fi
}

# Check if the Traefik container is already running
function isContainerRunning() {
  local container="$1" running_names
  local docker_cmd="docker"
  [ "${OS_NUMBER}" -ne 3 ] || docker_cmd="docker.exe"
  command -v "${docker_cmd}" >/dev/null 2>&1 || return 2
  running_names=$("${docker_cmd}" ps --format '{{.Names}}' 2>/dev/null) || return 2
  if printf '%s\n' "${running_names}" | grep -Fxq -- "${container}"; then
    return 0
  fi
  return 1
}

# lock a folder path
function lockFolder() {
  cat <<EOF
# Apache 2.4+
<IfModule mod_authz_core.c>
 Require all denied
</IfModule>

# Apache 2.0-2.2
<IfModule !mod_authz_core.c>
 Deny from all
</IfModule>
EOF
}

# clear the main environment variables
function quitProgram() {
  ####### CLEAR ALL
  unset VDM_PUID
  unset VDM_PGID
  unset VDM_CONTAINER_TYPE
  unset VDM_TASK
  unset VDM_SRC_PATH
  unset VDM_REPO_PATH
  unset VDM_PROJECT_PATH
  unset VDM_DOMAIN
  unset VDM_MULTI_DOMAIN
  unset VDM_SECURE
  unset VDM_SECURE_CLOUDFLARE
  unset VDM_UPDATE_HOST
  unset VDM_CONTAINER
  unset VDM_ACCESS_TOKEN
  # exit at this point
  exit 0
}

# do we allow multiple domains
function allowMultiDomains() {
  # Allow multiple domains
  setMultiDomainSwitch || return $?
  # allow multi domain setup
  if [ "${VDM_MULTI_DOMAIN:-false}" = true ]; then
    # yes we do
    return 0
  fi
  # now we don't
  return 1
}

# do we allow multiple domains
function allowEditHostFile() {
  # check if we allow host file updates
  setUpdateHostFile || return $?
  # allow multi domain setup
  if [ "${VDM_UPDATE_HOST:-false}" = true ]; then
    # yes we do
    return 0
  fi
  # now we don't
  return 1
}

# to set a global multiple domain file and values
function saveMultiDomain() {
  # set some locals
  local domain_name
  local src_path_domain
  # Whitespace-only input is an empty selection; malformed domains are refused.
  domain_name="${1:-}"
  [[ "${domain_name}" =~ [^[:space:]] ]] || return 0
  if ! isValidDomain "${domain_name}"; then
    echo >&2 "ERROR: Invalid domain: ${domain_name}"
    return 17
  fi
  src_path_domain="${VDM_SRC_PATH}/.domains"
  # check that we have a domain string
  if [ -n "${domain_name}" ]; then
    # make sure the folder exists
    mkdir -p "${VDM_SRC_PATH}" || return 1
    # if the file does not exist, create it and set the proper permissions
    if [ ! -f "${src_path_domain}" ]; then
      touch "${src_path_domain}" || return 1
      chmod 600 "${src_path_domain}" || return 1
    fi
    # check if the domain is not already in the file, and if not, add it
    if ! grep -Fxq -- "${domain_name}" "${src_path_domain}"; then
      printf '%s\n' "${domain_name}" >>"${src_path_domain}" || return 1
    fi
  fi
  # we return true
  return 0
}

# Delete a global environment variable from .env
function deleteEnvVariable() {
	# Key we want to remove
	local env_key="${1:-}"

	# Only proceed if key provided and file exists
	[ -z "${env_key}" ] && return 0
	[ ! -f "${VDM_SRC_PATH}/.env" ] && return 0

	# Escape regex special chars in the key
	local safe_key
	safe_key="$(printf '%s\n' "${env_key}" | sed 's/[]\/$*.^|[]/\\&/g')"

	# Create temporary file
	local tmp_file="${VDM_SRC_PATH}/.env_tmp"

	# Filter the .env file and remove matching line(s)
	if grep -E -v "^${safe_key}=.*$" "${VDM_SRC_PATH}/.env" > "${tmp_file}"; then
		# Preserve original permissions (GNU stat, then BSD stat on macOS)
		local env_mode
		env_mode=$(stat -c '%a' "${VDM_SRC_PATH}/.env" 2>/dev/null || stat -f '%Lp' "${VDM_SRC_PATH}/.env" 2>/dev/null)
		[ -n "${env_mode}" ] && chmod "${env_mode}" "${tmp_file}"
		mv "${tmp_file}" "${VDM_SRC_PATH}/.env"
	else
		rm -f "${tmp_file}"
		return 1
	fi

	return 0
}

# delete multiple domains
function deleteMultiDomains() {
  local menu_options=()
  local domains domain answer remove remove_domain tmp_file filter_status
  local array_answer=()
  local i=0
  local domain_file="${VDM_SRC_PATH}/.domains"

  if [ -f "${domain_file}" ] && readarray -t domains <"${domain_file}"; then
    if [ "${#domains[@]}" -gt 0 ]; then
      for domain in "${domains[@]}"; do
        [ -n "${domain}" ] || continue
        menu_options+=("${domain}" "${domain}" "OFF")
        i=$((i + 1))
      done

      [ "${i}" -gt 0 ] || return 0

      answer=$(whiptail --title "Delete Domains" --checklist \
        "Select the domain/s you would like to delete" 20 112 $i \
        "${menu_options[@]}" \
        --backtitle "${BACK_TITLE}" --nocancel --notags 3>&1 1>&2 2>&3) || return 1

      if [ -n "${answer}" ]; then
        IFS=' ' read -r -a array_answer <<<"${answer[@]}"
        for remove in "${array_answer[@]}"; do
          remove_domain="${remove//\"/}"
          tmp_file=$(mktemp "${domain_file}.XXXXXX") || return 1
          # Keep the domain list private when replacing it atomically.
          if ! cp -p -- "${domain_file}" "${tmp_file}"; then
            rm -f -- "${tmp_file}"
            return 1
          fi
          grep -Fvx -- "${remove_domain}" "${domain_file}" >"${tmp_file}"
          filter_status=$?
          # grep returns 1 when the last entry is removed: that is success.
          if [ "${filter_status}" -le 1 ]; then
            mv -- "${tmp_file}" "${domain_file}" || { rm -f -- "${tmp_file}"; return 1; }
          else
            rm -f -- "${tmp_file}"
            return "${filter_status}"
          fi
        done
      fi
    fi
  fi
}

# Match whole host aliases, ignoring comments, whitespace and letter case.
function hostFileHasHost() {
  local hostname="$1" host_file="$2"
  [ -f "${host_file}" ] || return 1
  awk -v hostname="${hostname}" '
    { sub(/\r$/, ""); sub(/#.*/, "") }
    { for (i = 2; i <= NF; i++) if (tolower($i) == tolower(hostname)) found = 1 }
    END { exit !found }
  ' "${host_file}"
}

# check if expert mode is on
function isExpert() {
  # check if its set
  if [ -n "${VDM_EXPERT_MODE}" ] && [ "${VDM_EXPERT_MODE}" = "true" ]; then
    # is expert
    return 0
  else
    # not expert
    return 1
  fi
}

# check if some thing is a function
function isFunc() {
  declare -F "$1" >/dev/null
}

# Update the host file for Linux and macOS
function updateHostFile_unix() {
  local allow_status
  local hostname="${1:-$VDM_SUBDOMAIN}.${2:-$VDM_DOMAIN}"
  # check if we should add to host file
  if allowEditHostFile; then
    if ! isValidDomain "${hostname}"; then
      showError "Invalid host name: ${hostname}"
      return 17
    fi
    # check if already in host file
    if hostFileHasHost "${hostname}" /etc/hosts; then
      showNotice "${USER^}, ${1:-$VDM_SUBDOMAIN}.${2:-$VDM_DOMAIN} is already in the /etc/hosts file."
    elif (whiptail --yesno "${USER^}, to add the ${1:-$VDM_SUBDOMAIN}.${2:-$VDM_DOMAIN} entry to your host file we need sudo privileges." \
      --title "Give sudo Privileges" --backtitle "${BACK_TITLE}" 8 112); then
      # add the domain to the host file
      if ! printf '127.0.0.1       %s\n' "${hostname}" | sudo tee -a /etc/hosts >/dev/null; then
        showError "Failed to add ${hostname} to /etc/hosts."
        return 1
      fi
      # show notice
      showNotice "${USER^}, ${1:-$VDM_SUBDOMAIN}.${2:-$VDM_DOMAIN} was added to the /etc/hosts file."
    fi
  else
    allow_status=$?
    [ "${allow_status}" -eq 1 ] || return "${allow_status}"
  fi
}

# Manually edit the host file for Linux and macOS
function editHostFile_unix() {
  # check if we should add to host file
  if allowEditHostFile; then
    # if this container is enabled ask if it should be redeployed
    if (whiptail --yesno "To edit the host file we need sudo privileges.\n[Only continue if you know what your doing!]" \
      --title "Give sudo Privileges" --backtitle "${BACK_TITLE}" 15 112); then
      # give little heads-up
      showNotice "${USER^}, to save the changes you've made or to just close the file again press:\n\n[ctrl+x] with nano on ubuntu." 13
      # lets open the file with nano for now
      sudo "${EDITOR:-nano}" /etc/hosts
    fi
  fi
}

# Update the host file for Windows (MSYS/Cygwin)
function updateHostFile_windows() {
  local allow_status
  local subdomain=${1:-$VDM_SUBDOMAIN}
  local domain=${2:-$VDM_DOMAIN}
  local host_file="/c/Windows/System32/drivers/etc/hosts"

  if allowEditHostFile; then
    if ! isValidDomain "${subdomain}.${domain}"; then
      showError "Invalid host name: ${subdomain}.${domain}"
      return 17
    fi
    if hostFileHasHost "${subdomain}.${domain}" "$host_file"; then
      showNotice "${USER^}, ${subdomain}.${domain} is already in the hosts file."
    elif (whiptail --yesno "${USER^}, to add the ${subdomain}.${domain} entry to your host file we need administrative privileges." \
      --title "Give administrative Privileges" --backtitle "${BACK_TITLE}" 8 112); then
      if ! printf '127.0.0.1       %s\n' "${subdomain}.${domain}" | sudo tee -a "$host_file" >/dev/null; then
        showError "Failed to add ${subdomain}.${domain} to the hosts file."
        return 1
      fi
      showNotice "${USER^}, ${subdomain}.${domain} was added to the hosts file."
    fi
  else
    allow_status=$?
    [ "${allow_status}" -eq 1 ] || return "${allow_status}"
  fi
}

# Manually edit the host file for Windows (MSYS/Cygwin)
function editHostFile_windows() {
  local host_file="/c/Windows/System32/drivers/etc/hosts"

  if allowEditHostFile; then
    if (whiptail --yesno "To edit the host file we need administrative privileges.\n[Only continue if you know what you're doing!]" \
      --title "Give administrative Privileges" --backtitle "${BACK_TITLE}" 15 112); then
      showNotice "${USER^}, to save the changes you've made or to just close the file again press:\n\n[ctrl+x] with nano." 13
      sudo "${EDITOR:-nano}" "$host_file"
    fi
  fi
}

# Update the host file (dynamically calls the correct OS function)
function updateHostFile() {
  case "$OS_NUMBER" in
    1|2)
      updateHostFile_unix "$@"
      ;;
    3)
      updateHostFile_windows "$@"
      ;;
    *)
      echo >&2 "ERROR: Unsupported operating system."
      exit 1
      ;;
  esac
}

# Manually edit the host file (dynamically calls the correct OS function)
function editHostFile() {
  case "$OS_NUMBER" in
    1|2)
      editHostFile_unix
      ;;
    3)
      editHostFile_windows
      ;;
    *)
      echo >&2 "ERROR: Unsupported operating system."
      exit 1
      ;;
  esac
}

# the manually edit the config file
function editConfigFile() {
  # check if the file exist
  if [ -f "${VDM_SRC_PATH}/.env" ]; then
    # give little warning for less command ready people
    if (whiptail --yesno "Only continue if you know what your doing!\n\n\
    ${USER^}, to save the changes you've made or to just close the file again press:\n\n\
      [ctrl+x] with nano on ubuntu." --title "Continue to edit ${PROGRAM_NAME} global config." \
      --backtitle "${BACK_TITLE}" 15 112); then
      # all direct edit of the global config file
      "${EDITOR:-nano}" "${VDM_SRC_PATH}/.env"
    fi
  fi
}

# the manually edit the container env file
function openEnv() {
  # some local values
  local container_type="$1"
  # check if the file exist
  if [ -f "${VDM_REPO_PATH}/${container_type}/.env" ]; then
    # give little warning for less command ready people
    if (whiptail --yesno "Only continue if you know what your doing!\n\n\
    ${USER^}, to save the changes you've made or to just close the file again press:\n\n\
      [ctrl+x] with nano on ubuntu." --title "Continue to edit ${PROGRAM_NAME} ${container_type} env." \
      --backtitle "${BACK_TITLE}" 15 112); then
      # all direct edit of the container env file
      "${EDITOR:-nano}" "${VDM_REPO_PATH}/${container_type}/.env"
    fi
  else
    showError "${VDM_REPO_PATH}/${container_type}/.env does not exist, make sure you have at least one ${container_type} setup."
  fi
}

# Check if any hosts are set in the SSH config file
function hasRemoteSystemSet() {
  local ssh_config="${VDM_HOME_PATH}/.ssh/config"

  if [ ! -d "${VDM_HOME_PATH}/.ssh" ] || [ ! -f "${ssh_config}" ] ||
    ! grep -qiE '^[[:space:]]*Host[[:space:]]+[^#[:space:]]' "${ssh_config}"; then
      showError "To use this feature you must first set up the needed remote host details in (~/.ssh/config) to allow easy and secure SSH access."
      return 1
  fi

  return 0
}

# Get a selected remote system
function getRemoteSystem() {
  # The selected folder
  local answer

  if [ -f "${VDM_HOME_PATH}/.ssh/config" ]; then
    # We start the selection array
    local selected=()
    # Our counter
    local i=0
    # Add the remote systems
    while IFS= read -r remote_system; do
      # Load the remote systems
      selected+=("${remote_system}" "${remote_system}" "OFF")
      # Increment our pointer
      if [ "$i" -le 10 ]; then
        i=$((i + 1))
      fi
    done < <(awk 'tolower($1) == "host" { for (i = 2; i <= NF && $i !~ /^#/; i++) if ($i !~ /[*!?]/) print $i }' \
      "${VDM_HOME_PATH}/.ssh/config" | sort -u)

    # Add manual input option
    selected+=("Enter manually" "Enter manually" "OFF")

    # now make the selection
    answer=$(whiptail --title "Remote Systems" --radiolist \
      "Select the remote system you would like to use." 20 112 $i \
      "${selected[@]}" --backtitle "${BACK_TITLE}" --notags 3>&1 1>&2 2>&3)

    if [[ $answer == "Enter manually" ]]; then
      answer=$(getInputNow "Enter the remote host manually:" "" "Remote Host")
    fi
  else
    answer=$(getInputNow "Enter the remote host:" "" "Remote Host")
  fi

  # Return the answer
  echo "${answer:-none_selected}"
}

# get a selected migration type
function getMigrationType() {
  # the selected folder
  local answer
  # we start the selection array
  local selected=()
  # our counter
  local i=2
  # now check if this dir has sub dirs
  selected+=("push" "Push to Remote System" "ON")
  selected+=("pull" "Pull from Remote System" "OFF")
  # now make the selection
  answer=$(whiptail --title "Migration Type" --radiolist \
    "What kind of migration will be preformed?" 20 112 $i \
    "${selected[@]}" --backtitle "${BACK_TITLE}" --nocancel --notags 3>&1 1>&2 2>&3)
  # return the answer
  echo "${answer:-push}"
}

# Check if the remote .env file exists using the remote user's home directory
function remoteEnvFileExists() {
  local remote_system="$1"

  # Expand HOME on the remote host, never on the local machine.
  ssh -- "${remote_system}" '[ -f "$HOME/.config/octojoom/.env" ]'
}

# Quote one argument for the remote POSIX shell (including embedded apostrophes).
function quoteRemoteArgument() {
  printf "'%s'" "${1//\'/\'\\\'\'}"
}

# Migration destinations must name a directory below an absolute base path.
function isSafeMigrationPath() {
  local path="$1"
  [[ "${path}" == /* && "${path}" != / && "${path}" != *$'\n'* ]] || return 1
  case "/${path#/}/" in
  *'/../'* | *'/./'* | *'//'*) return 1 ;;
  esac
}

# Get a specific value from the remote .env file using the remote user's home directory
function getRemoteEnvValue() {
  local remote_system="$1"
  local env_key="$2"
  local remote_env_value

  if [[ ! "${env_key}" =~ ^[A-Za-z_][A-Za-z0-9_]*$ ]] ||
    ! remoteEnvFileExists "${remote_system}" ||
    ! remote_env_value=$(ssh -- "${remote_system}" "grep \"^${env_key}=\" \"\$HOME/.config/octojoom/.env\""); then
    printf '%s\n' none_found
    return 1
  fi
  # Match local dotenv loading: the last assignment wins, and values are data.
  remote_env_value="${remote_env_value##*$'\n'}"
  if ! decodeEnvValue "${remote_env_value#*=}" remote_env_value || [ -z "${remote_env_value}" ]; then
    printf '%s\n' none_found
    return 1
  fi
  printf '%s\n' "${remote_env_value}"
}

# Pull the remote container migration
function pullContainerMigration() {
  # set some local variables
  local local_path="$1"
  local container_path="$2"
  local remote="$3"
  local remote_repo_path

  if ! remote_repo_path=$(getRemoteEnvValue "${remote}" "VDM_REPO_PATH") ||
    [ "${remote_repo_path}" = none_found ]; then
    showError "Remote system does not appear to have ${PROGRAM_NAME} installed, or your access was denied. Therefore the migration has been cancelled!"
    return 1
  fi
  pullRemoteFolder "${local_path}" "${remote_repo_path%/}/${container_path}" "${remote}"
}

# Push the remote container migration
function pushContainerMigration() {
  # set some local variables
  local local_path="$1"
  local container_path="$2"
  local remote="$3"
  local remote_repo_path

  if ! remote_repo_path=$(getRemoteEnvValue "${remote}" "VDM_REPO_PATH") ||
    [ "${remote_repo_path}" = none_found ]; then
    showError "Remote system does not appear to have ${PROGRAM_NAME} installed, or your access was denied. Therefore the migration has been cancelled!"
    return 1
  fi
  local remote_path="${remote_repo_path%/}/${container_path}" tar_path
  if ! [ -d "${local_path}" ] || ! isSafeMigrationPath "${remote_path}"; then
    showError "Migration failed: the source directory or remote destination is invalid."
    return 1
  fi
  if ! tar_path=$(tarAndMoveTempBackup "${local_path}" "${local_path}"); then
    showError "The PUSH failed while creating the container archive."
    return 1
  fi
  pushArchivedMigration "${tar_path}" "${remote_path}" "${remote}" || return 1
  showNotice "The PUSH of ${local_path} to ${remote}:${remote_path} was a success." 13
  return 0
}

# Pull the remote directory migration
function pullDirectoryMigration() {
  # set some local variables
  local local_path="$1"
  local directory_name="$2"
  local remote="$3"
  local remote_project_path

  if ! remote_project_path=$(getRemoteEnvValue "${remote}" "VDM_PROJECT_PATH") ||
    [ "${remote_project_path}" = none_found ]; then
    showError "Remote system does not appear to have ${PROGRAM_NAME} installed, or your access was denied. Therefore the migration has been cancelled!"
    return 1
  fi
  pullRemoteFolder "${local_path}" "${remote_project_path%/}/${directory_name}" "${remote}"
}

# Package on the source host and verify the single downloaded archive before
# extracting or replacing any existing local data.
function pullRemoteFolder() {
  local local_path="$1" remote_path="$2" remote="$3"
  local staging_path workspace remote_workspace remote_tar backup_path keep_backup=false
  if ! isSafeMigrationPath "${local_path}" || ! isSafeMigrationPath "${remote_path}" ||
    [ -L "${local_path}" ] || ! remoteFolderExists "${remote_path}" "${remote}"; then
    showError "The PULL failed: the source directory is unavailable or a migration path is invalid."
    return 1
  fi
  if ! mkdir -p -- "$(dirname "${local_path}")" ||
    ! workspace=$(mktemp -d "${local_path}.migration.XXXXXX"); then
    showError "The PULL failed: could not create a local staging directory."
    return 1
  fi
  staging_path="${workspace}/payload"
  # The archive is created privately on the source, including when root access
  # is needed to read project files. Nothing is rsynced as a loose directory.
  if ! remote_workspace=$(ssh -- "${remote}" "umask 077;
    [ ! -L $(quoteRemoteArgument "${remote_path}") ] || exit 1;
    workspace=\$(mktemp -d \"\${TMPDIR:-/tmp}/octojoom-pull.XXXXXX\") || exit 1;
    trap 'rm -rf -- \"\$workspace\"' 0;
    if tar -czf \"\$workspace/archive.tar.gz\" -C $(quoteRemoteArgument "${remote_path}") . ||
      sudo -n tar -czf \"\$workspace/archive.tar.gz\" -C $(quoteRemoteArgument "${remote_path}") .; then
      printf '%s\\n' \"\$workspace\"; trap - 0;
    else exit 1; fi") || ! isSafeMigrationPath "${remote_workspace}" ||
    [[ ! "${remote_workspace##*/}" =~ ^octojoom-pull\.[[:alnum:]]{6}$ ]]; then
    rm -rf -- "${workspace}"
    showError "The PULL failed while packaging the remote source; the local directory was preserved."
    return 1
  fi
  remote_tar="${remote_workspace}/archive.tar.gz"
  if ! rsync -av --protect-args -- "${remote}:${remote_tar}" "${workspace}/archive.tar.gz" ||
    ! transferTarWasSuccessful "${workspace}/archive.tar.gz" "${remote_tar}" "${remote}" ||
    ! migrationValidateTar "${workspace}/archive.tar.gz" folder ||
    ! mkdir -- "${staging_path}" ||
    ! tar --no-same-owner -xzf "${workspace}/archive.tar.gz" -C "${staging_path}"; then
    removeRemoteFolder "${remote_workspace}" "${remote}" || true
    rm -rf -- "${workspace}" || sudo rm -rf -- "${workspace}"
    showError "The PULL of ${remote}:${remote_path} failed; the local directory was preserved."
    return 1
  fi
  if ! removeRemoteFolder "${remote_workspace}" "${remote}"; then
    rm -rf -- "${workspace}" || sudo rm -rf -- "${workspace}"
    showError "The PULL stopped because the remote temporary archive could not be removed: ${remote}:${remote_workspace}"
    return 1
  fi
  backup_path="${local_path}_backup_$(date +%Y%m%d%H%M%S)_${BASHPID}_${RANDOM}"
  if [ -e "${local_path}" ]; then
    if whiptail --yesno "${USER^}, would you like to retain a backup of the local directory?" \
      --title "Backup Local" --backtitle "${BACK_TITLE}" 15 112; then
      keep_backup=true
    fi
    if [ -e "${backup_path}" ] || ! mv -- "${local_path}" "${backup_path}"; then
      rm -rf -- "${workspace}" || sudo rm -rf -- "${workspace}"
      showError "The PULL failed: could not preserve the local directory."
      return 1
    fi
  fi
  if ! mv -- "${staging_path}" "${local_path}"; then
    if [ -e "${backup_path}" ] && ! mv -- "${backup_path}" "${local_path}"; then
      showError "The PULL publication and rollback failed. The original directory is retained at ${backup_path}."
    else
      showError "The PULL failed while publishing the verified directory."
    fi
    rm -rf -- "${workspace}" || sudo rm -rf -- "${workspace}"
    return 1
  fi
  rm -rf -- "${workspace}" || sudo rm -rf -- "${workspace}" || return 1
  if [ "${keep_backup}" = false ] && [ -e "${backup_path}" ] &&
    ! (rm -rf -- "${backup_path}" || sudo rm -rf -- "${backup_path}"); then
    showError "The PULL completed, but the previous directory could not be removed: ${backup_path}"
    return 1
  fi
  showNotice "The PULL of ${remote}:${remote_path} to ${local_path} was a success." 13
  return 0
}

# Transfer exactly one compressed archive into a private destination workspace.
# The source archive remains available for recovery until publication succeeds.
function pushArchivedMigration() {
  local tar_path="$1" remote_path="$2" remote="$3" workspace remote_tar staging_path
  if ! [ -f "${tar_path}" ] || ! isSafeMigrationPath "${remote_path}" ||
    ! migrationValidateTar "${tar_path}" folder; then
    showError "The PUSH failed: the archive contains an unsupported or unsafe entry. The local archive was retained at ${tar_path}."
    return 1
  fi
  if ! workspace=$(ssh -- "${remote}" "umask 077; mkdir -p -- $(quoteRemoteArgument "$(dirname "${remote_path}")") &&
    mktemp -d $(quoteRemoteArgument "${remote_path}.migration.XXXXXX")") ||
    ! isSafeMigrationPath "${workspace}" || [[ "${workspace}" != "${remote_path}.migration."* ]]; then
    showError "The PUSH failed while creating a private remote workspace. The local archive was retained at ${tar_path}."
    return 1
  fi
  remote_tar="${workspace}/archive.tar.gz"
  staging_path="${workspace}/payload"
  if ! moveTarToRemote "${tar_path}" "${remote_tar}" "${remote}" ||
    ! transferTarWasSuccessful "${tar_path}" "${remote_tar}" "${remote}" ||
    ! remoteUntarGz "${remote_tar}" "${staging_path}" "${remote}" ||
    ! publishRemoteMigration "${staging_path}" "${remote_path}" "${remote}"; then
    removeRemoteFolder "${workspace}" "${remote}" || true
    showError "The PUSH to ${remote}:${remote_path} failed. The local archive was retained at ${tar_path}."
    return 1
  fi
  if ! removeRemoteFolder "${workspace}" "${remote}" || ! rm -f -- "${tar_path}"; then
    showError "The PUSH completed, but temporary archive cleanup failed. Check ${remote}:${workspace} and ${tar_path}."
    return 1
  fi
}

# Publish a verified staging directory, retaining the original if the rename fails.
function publishRemoteMigration() {
  local staging_path="$1" remote_path="$2" remote="$3" keep_backup=false
  local quoted_staging quoted_path quoted_backup backup_path publish_status
  isSafeMigrationPath "${staging_path}" && isSafeMigrationPath "${remote_path}" || return 1
  if remoteFolderExists "${remote_path}" "${remote}" &&
    whiptail --yesno "${USER^}, would you like to backup the remote directory?" \
      --title "Backup Remote" --backtitle "${BACK_TITLE}" 15 112; then
    keep_backup=true
  fi
  backup_path="${remote_path}_backup_$(date +%Y%m%d%H%M%S)_${BASHPID}_${RANDOM}"
  quoted_staging=$(quoteRemoteArgument "${staging_path}")
  quoted_path=$(quoteRemoteArgument "${remote_path}")
  quoted_backup=$(quoteRemoteArgument "${backup_path}")
  if ssh -- "${remote}" "[ -d ${quoted_staging} ] && [ ! -e ${quoted_backup} ] || exit 20;
    if [ -e ${quoted_path} ]; then mv -- ${quoted_path} ${quoted_backup} || exit 20; fi;
    if mv -- ${quoted_staging} ${quoted_path}; then
      if [ '${keep_backup}' = false ] && [ -e ${quoted_backup} ]; then
        rm -rf -- ${quoted_backup} || sudo -n rm -rf -- ${quoted_backup} || exit 22;
      fi;
    else
      if [ -e ${quoted_backup} ]; then mv -- ${quoted_backup} ${quoted_path} || exit 23; fi;
      exit 21;
    fi"; then
    return 0
  else
    publish_status=$?
  fi
  case "${publish_status}" in
    22) showError "The verified migration was published, but the previous directory could not be removed: ${remote}:${backup_path}" ;;
    23) showError "Remote publication and rollback failed. The original directory is retained at ${remote}:${backup_path}." ;;
    255) showError "The SSH connection failed during publication. Check ${remote}:${remote_path} and the recovery backup ${backup_path} before retrying." ;;
  esac
  return 1
}

# Push the remote directory migration
function pushDirectoryMigration() {
  # set some local variables
  local local_path="$1"
  local directory_name="$2"
  local remote="$3"
  local remote_project_path

  if ! remote_project_path=$(getRemoteEnvValue "${remote}" "VDM_PROJECT_PATH") ||
    [ "${remote_project_path}" = none_found ]; then
    showError "Remote system does not appear to have ${PROGRAM_NAME} installed, or your access was denied. Therefore the migration has been cancelled!"
    return 1
  fi
  local backup_dir tar_path remote_path
  remote_path="${remote_project_path%/}/${directory_name}"
  if ! [ -d "${local_path}" ] || ! isSafeMigrationPath "${remote_path}"; then
    showError "Migration failed: the source directory or remote destination is invalid."
    return 1
  fi
  if ! backup_dir=$(createTempBackup "${local_path}"); then
    showError "The PUSH failed while creating a temporary backup."
    return 1
  fi
  if ! chownBackup "${backup_dir}" || ! tar_path=$(tarAndMoveTempBackup "${local_path}" "${backup_dir}"); then
    sudo rm -rf -- "${backup_dir}"
    showError "The PUSH failed while preparing the archive."
    return 1
  fi
  if ! (rm -rf -- "${backup_dir}" || sudo rm -rf -- "${backup_dir}"); then
    showError "The PUSH failed while removing the temporary copy. The local archive was retained at ${tar_path}."
    return 1
  fi
  pushArchivedMigration "${tar_path}" "${remote_path}" "${remote}" || return 1
  if whiptail --yesno "${USER^}, would you like to fix the permissions of this remote directory?\nWe will start ${PROGRAM_NAME} on the remote server; navigate to the fix, and exit when done." \
    --title "Permissions Fix" --backtitle "${BACK_TITLE}" 15 112; then
    connectToRemoteSystem "${remote}" || return 1
  fi
  showNotice "The PUSH of ${local_path} to ${remote}:${remote_path} was a success." 13
  return 0
}

# Create a temporary backup of the folder with root access
function createTempBackup() {
  local source_dir="$1"
  local backup_dir
  [ -d "${source_dir}" ] || return 1
  backup_dir=$(mktemp -d "${TMPDIR:-/tmp}/octojoom-backup.XXXXXX") || return 1
  if ! sudo cp -a -- "${source_dir}/." "${backup_dir}/"; then
    sudo rm -rf -- "${backup_dir}"
    return 1
  fi
  printf '%s\n' "${backup_dir}"
}

# Create a private temporary tar.gz archive without overwriting an existing backup.
function tarAndMoveTempBackup() {
  local source_dir="$1"
  local backup_dir="$2"
  local tar_path
  [ -d "${source_dir}" ] && [ -d "${backup_dir}" ] || return 1
  tar_path=$(mktemp "${TMPDIR:-/tmp}/octojoom-archive.XXXXXX") || return 1
  if ! tar -czf "${tar_path}" -C "${backup_dir}" .; then
    rm -f -- "${tar_path}"
    return 1
  fi
  printf '%s\n' "${tar_path}"
}

# Change the ownership of the backup directory to the current user
function chownBackup() {
  local backup_dir="$1"
  sudo chown -R "$(id -u):$(id -g)" -- "${backup_dir}"
}

# Check if the folder exists on the remote server
function remoteFolderExists() {
  local remote_path="$1"
  local remote="$2"

  ssh -- "${remote}" "[ -d $(quoteRemoteArgument "${remote_path}") ]"
}

# run Octojoom on a remote system
function connectToRemoteSystem() {
  # set some local variables
  local remote_system="${1:-none_set}"
  # get remote system
  if [ "${remote_system}" == "none_set" ]; then
    remote_system=$(getRemoteSystem)
  fi
  # make sure we have a remote
  if [ ${#remote_system} -ge 2 ] && [ "${remote_system}" != "none_selected" ]; then
    showNotice "We will first validate that the remote system has ${PROGRAM_NAME,,} config settings in place!" 13
    if remoteEnvFileExists "${remote_system}"; then
      if (whiptail --yesno "${USER^} we found ${PROGRAM_NAME,,} config settings on the ${remote_system}. Please take note of the following important information.\n\nSince we will start ${PROGRAM_NAME,,} on ${remote_system} it will not look that different, seeing that it has the same user graphical interface. Yet, whatever changes you make on ${remote_system} WILL PERMINANTLY effect this remote system, and can not be undone!!!\n\nAre you ready to connect to ${remote_system}:${PROGRAM_NAME,,}?" \
        --title "Confirm ${remote_system} Connection" --backtitle "${BACK_TITLE}" 15 112); then
        showNotice "Connection to ${remote_system} will now be made!" 13
        if ! ssh -t -- "${remote_system}" "bash octojoom"; then
          showError "The connection or remote ${PROGRAM_NAME} session failed."
          return 1
        fi
        showNotice "You have been disconnected from ${remote_system}!" 13
        return 0
      else
        showNotice "The connection to ${remote_system} was cancelled!" 13
        return 1
      fi
    else
      showError "Remote system does not appear to have ${PROGRAM_NAME,,} installed, or your access was denied. Therefore the connection has been closed!"
      return 1
    fi
  fi
  showError "Connection to the remote system was cancelled since no remote system was selected."
  return 1
}

# Change the ownership of the remote folder to the current user
function chownRemoteFolder() {
  local remote_path="$1"
  local remote="$2"

  isSafeMigrationPath "${remote_path}" || return 1
  # Use the remote account's IDs, which need not match the local username.
  ssh -t -- "${remote}" "sudo chown -R \"\$(id -u):\$(id -g)\" -- $(quoteRemoteArgument "${remote_path}")"
}

# Check if the folder exists on the remote server, and if so, rename it for backup purposes
function backupRemoteFolder() {
  local remote_path="$1"
  local remote="$2"
  local backup_name quoted_path quoted_backup
  isSafeMigrationPath "${remote_path}" || return 1
  backup_name="${remote_path}_backup_$(date +%Y%m%d%H%M%S)_${BASHPID}_${RANDOM}"
  quoted_path=$(quoteRemoteArgument "${remote_path}")
  quoted_backup=$(quoteRemoteArgument "${backup_name}")
  ssh -- "${remote}" "[ -d ${quoted_path} ] && [ ! -e ${quoted_backup} ] && mv -- ${quoted_path} ${quoted_backup}"
}

# remove the remote folder
function removeRemoteFolder() {
  local remote_path="$1"
  local remote="$2"
  isSafeMigrationPath "${remote_path}" || return 1
  ssh -- "${remote}" "if [ -d $(quoteRemoteArgument "${remote_path}") ]; then \
    rm -rf -- $(quoteRemoteArgument "${remote_path}") || sudo -n rm -rf -- $(quoteRemoteArgument "${remote_path}"); fi"
}

# Prep remote folder
function prepRemoteFolder() {
  local remote_path="$1"
  local remote="$2"

  isSafeMigrationPath "${remote_path}" || return 1
  ssh -- "${remote}" "mkdir -p -- $(quoteRemoteArgument "${remote_path}")"
}

# Remotely extract a tar.gz file to a specified folder on the remote host
function remoteUntarGz() {
  local remote_file_path="$1"
  local remote_extract_path="$2"
  local remote="$3"

  isSafeMigrationPath "${remote_file_path}" && isSafeMigrationPath "${remote_extract_path}" || return 1
  local remote_script
  # Send the validator with the operation so legacy remote installations also
  # reject traversal, links and special entries before writing archive contents.
  remote_script="$(declare -f migrationValidateTar)
    migrationValidateTar $(quoteRemoteArgument "${remote_file_path}") folder &&
    [ ! -e $(quoteRemoteArgument "${remote_extract_path}") ] &&
    (umask 077; mkdir -- $(quoteRemoteArgument "${remote_extract_path}")) &&
    tar --no-same-owner -xzf $(quoteRemoteArgument "${remote_file_path}") -C $(quoteRemoteArgument "${remote_extract_path}") &&
    rm -f -- $(quoteRemoteArgument "${remote_file_path}")"
  ssh -- "${remote}" "bash -c $(quoteRemoteArgument "${remote_script}")"
}

# Transfer the folder to the remote server using rsync
function syncFolder() {
  local local_path="$1"
  local remote_path="$2"
  local remote="$3"
  rsync -avz --protect-args --delete -- "${local_path}/" "${remote}:${remote_path}/"
}

# Move/copy the local tar file to the remote server
function moveTarToRemote() {
  local local_path="$1"
  local remote_path="$2"
  local remote="$3"

  # rsync protects remote paths with spaces and quotes on all supported SSH versions.
  [ -f "${local_path}" ] || return 1
  rsync -av --protect-args -- "${local_path}" "${remote}:${remote_path}"
}

# Sync the local folder to the remote server and remove the local backup
function syncWithRemote() {
  local local_path="$1"
  local remote_path="$2"
  local remote="$3"

  prepRemoteFolder "${remote_path}" "${remote}" || return 1

  syncFolder "${local_path}" "${remote_path}" "${remote}"
}

# Check if the transfer was successful by comparing local and remote directory contents
function transferWasSuccessful() {
  local local_path="$1"
  local remote_path="$2"
  local remote="$3"

  local rsync_output
  # Quiet itemized output includes changed files, metadata, and deletions.
  rsync_output=$(rsync -az --protect-args --dry-run --checksum --delete --itemize-changes \
    --out-format='%i %n%L' -- "${local_path}/" "${remote}:${remote_path}/") || return 1
  [ -z "${rsync_output}" ]
}

# Check if the transfer was successful by comparing local and remote zip file checksums
function transferTarWasSuccessful() {
  local local_path="$1"
  local remote_path="$2"
  local remote="$3"

  local local_checksum remote_checksum quoted_path
  [ -f "${local_path}" ] || return 1
  if command -v sha256sum >/dev/null 2>&1; then
    local_checksum=$(sha256sum -- "${local_path}") || return 1
  else
    local_checksum=$(shasum -a 256 -- "${local_path}") || return 1
  fi
  quoted_path=$(quoteRemoteArgument "${remote_path}")
  remote_checksum=$(ssh -- "${remote}" "if command -v sha256sum >/dev/null 2>&1; then \
    sha256sum -- ${quoted_path}; else shasum -a 256 -- ${quoted_path}; fi") || return 1
  local_checksum="${local_checksum%% *}"
  remote_checksum="${remote_checksum%% *}"
  [[ "${local_checksum}" =~ ^[[:xdigit:]]{64}$ && "${remote_checksum}" =~ ^[[:xdigit:]]{64}$ &&
    "${local_checksum}" = "${remote_checksum}" ]]
}

#####################################################################################################################VDM
######################################## CLI MENU ʕ•ᴥ•ʔ

# help message
function showHelp() {
  cat <<EOF
Usage: octojoom [OPTION...]
	Options
	======================================================
   --type <type>
	set type you would like to work with
	example: octojoom --type joomla
	======================================================
   --task <task>
	set type of task you would like to perform
	example: octojoom --task setup
	======================================================
   --container <container.domain.name>
	Directly enabling or disabling a container with
	  the type=joomla and task=enable/disable set
	The container must exist, which means it was
	  setup previously
	Used without type and task Joomla-Enable is (default)
	example: octojoom --container "io.vdm.dev"
	======================================================
   --update
	to update your install
	example: octojoom --update
	======================================================
   --access-token <token>
	to update the program you will need an access token
	from https://git.vdm.dev/user/settings/applications
	example: octojoom --access-token xxxxxxxxxxx
	======================================================
   --uninstall
	to uninstall this script
	example: octojoom --uninstall
	======================================================
	AVAILABLE FOR TO ANY CONTAINER
	======================================================
   -k|--key <key>
	set key for the docker compose container naming
	!! no spaces allowed in the key !!
	example: octojoom -k="vdm"
	example: octojoom --key="vdm"
	======================================================
   -e|--env-key <key>
	set key for the environment variable naming
	!! no spaces allowed in the key & must be UPPERCASE !!
	example: octojoom -e="VDM"
	example: octojoom --env-key="VDM"
	======================================================
   -d|--domain <domain.com>
	set key website domain
	!! must be domain.tld !!
	example: octojoom -d="joomla.org"
	example: octojoom --domain="joomla.org"
	======================================================
   -s|--sub-domain <domain.com>
	set key website sub domain
	!! no spaces allowed in the sub domain !!
	example: octojoom -s="jcb"
	example: octojoom --sub-domain="jcb"
	======================================================
	AVAILABLE FOR JOOMLA CONTAINER
	======================================================
   -j|--joomla-version <version-tag>
	see available tags here https://hub.docker.com/_/joomla
	example: octojoom -j=6.0
	example: octojoom --joomla-version=6.0
	======================================================
	AVAILABLE FOR OPENSSH CONTAINER
	======================================================
   -u|--username <username>
	set username of the container
	example: octojoom -u="ubuntu"
	example: octojoom --username="ubuntu"
	======================================================
   --uid <id>
	set container user id
	example: octojoom --uid=1000
	======================================================
   --gid <id>
	set container user group id
	example: octojoom --gid=1000
	======================================================
   -p|--port <port>
	set ssh port to use
	!! do not use 22 !!
	example: octojoom -p=2239
	example: octojoom --port=2239
	======================================================
   --ssh-dir <dir>
	set ssh directory name found in the .ssh dir
	of this repo for the container keys
		This directory has separate files for
		each public key allowed to access
		the container
	example: octojoom --ssh-dir="teamname"
	======================================================
   --sudo
	switch to add the container user to the
	sudo group of the container
	example: octojoom --sudo
	======================================================
   -t|--time-zone <time/zone>
	set time zone of the container
	!! must valid time zone !!
	example: octojoom -t="Africa/Windhoek"
	example: octojoom --time-zone="Africa/Windhoek"
	======================================================
	HELP ʕ•ᴥ•ʔ
	======================================================
   -h|--help
	display this help menu
	example: octojoom -h
	example: octojoom --help
	======================================================
			${PROGRAM_NAME} v${_VERSION}
	======================================================
EOF
}

#####################################################################################################################VDM
######################################## CLI INPUT ¯\_(ツ)_/¯

# Read one scoped dotenv assignment without evaluating or exporting its value.
# The last assignment wins, matching OctoJoom's existing dotenv loader.
function migrationReadEnvValue() {
  local migration_file="$1" migration_name="$2" migration_target="$3"
  local migration_line migration_value='' migration_found=false
  [[ "$migration_name" =~ ^VDM_[A-Za-z0-9_]+$ && "$migration_target" =~ ^[A-Za-z_][A-Za-z0-9_]*$ ]] || return 1
  [ -f "$migration_file" ] && [ ! -L "$migration_file" ] || return 1
  while IFS= read -r migration_line || [ -n "$migration_line" ]; do
    migration_line="${migration_line%$'\r'}"
    [[ "$migration_line" =~ ^[[:space:]]*(#.*)?$ ]] && continue
    [[ "$migration_line" =~ ^[[:space:]]*(export[[:space:]]+)?(VDM_[A-Za-z0-9_]+)[[:space:]]*=[[:space:]]*(.*)$ ]] || return 1
    if [ "${BASH_REMATCH[2]}" = "$migration_name" ]; then
      decodeEnvValue "${BASH_REMATCH[3]}" migration_value || return 1
      [[ "$migration_value" != *$'\n'* && "$migration_value" != *$'\r'* ]] || return 1
      migration_found=true
    fi
  done < "$migration_file"
  "$migration_found" || return 1
  printf -v "$migration_target" '%s' "$migration_value"
}

# Generated Compose supports simple VDM placeholders and escaped dollar signs.
# Fail closed for shell variables, defaults, nesting, and hand-written forms.
function migrationComposeReferences() {
  local compose_file="$1" line rest name seen=' '
  [ -f "$compose_file" ] || return 1
  while IFS= read -r line || [ -n "$line" ]; do
    [[ "$line" =~ ^[[:space:]]*# ]] && continue
    rest="$line"
    while [[ "$rest" == *'$'* ]]; do
      rest="${rest#*\$}"
      if [[ "$rest" == '$'* ]]; then
        rest="${rest:1}"
        continue
      elif [[ "$rest" =~ ^\{(VDM_[A-Za-z0-9_]+)\} ]]; then
        name="${BASH_REMATCH[1]}"
        rest="${rest:${#BASH_REMATCH[0]}}"
      else
        return 1
      fi
      if [[ "$seen" != *" $name "* ]]; then
        printf '%s\n' "$name"
        seen+="$name "
      fi
    done
  done < "$compose_file"
}

function migrationValidateScopedEnv() {
  local compose_file="$1" env_file="$2" refs line name value seen=' '
  refs=$(migrationComposeReferences "$compose_file") || return 1
  refs=" ${refs//$'\n'/ } "
  while IFS= read -r line || [ -n "$line" ]; do
    [[ "$line" =~ ^(VDM_[A-Za-z0-9_]+)=(.*)$ ]] || return 1
    name="${BASH_REMATCH[1]}"
    [[ "$refs" == *" $name "* && "$seen" != *" $name "* ]] || return 1
    decodeEnvValue "${BASH_REMATCH[2]}" value || return 1
    seen+="$name "
  done < "$env_file"
  for name in $refs; do
    [[ "$seen" == *" $name "* ]] || return 1
  done
}

# Validate a tar before extraction. Escaped listings prevent embedded newlines
# and control characters from masquerading as separate, harmless member names.
# GNU tar and bsdtar both escape control characters in these listings.
function migrationValidateTar() {
  local archive="$1" layout="${2:-bundle}" names types member normalized type version
  local -A tar_seen=()
  local listing_options=()
  [ -f "$archive" ] && [ ! -L "$archive" ] || return 1
  version=$(tar --version 2>/dev/null) || return 1
  case "$version" in
    *'GNU tar'*) listing_options+=(--quoting-style=escape) ;;
    *bsdtar*|*libarchive*) ;; # bsdtar uses safe, escaped names by default.
    *) return 1 ;;
  esac
  names=$(LC_ALL=C TAR_OPTIONS='' tar "${listing_options[@]}" -tzf "$archive" 2>/dev/null) || return 1
  types=$(LC_ALL=C TAR_OPTIONS='' tar "${listing_options[@]}" -tvzf "$archive" 2>/dev/null) || return 1
  [ -n "$names" ] && [ -n "$types" ] || return 1
  while IFS= read -r type; do
    [[ "$type" == -* || "$type" == d* ]] || return 1
    [[ "${type:0:10}" != *[sS]* ]] || return 1
    [[ "$type" != *' link to '* && "$type" != *' -> '* ]] || return 1
  done <<< "$types"
  while IFS= read -r member; do
    # Keep the serialized function free of literal control characters: Cygwin
    # can remove a carriage return when reparsing the definition over SSH.
    [[ -n "$member" && "$member" != /* && "$member" != *\\* && "$member" != *[![:print:]]* ]] || return 1
    normalized="${member#./}"
    normalized="${normalized%/}"
    if [ -z "$normalized" ]; then
      [ "$member" = ./ ] && [ "$layout" = folder ] && continue
      return 1
    fi
    case "/${normalized}/" in
      *'/../'*|*'/./'*|*'//'*) return 1 ;;
    esac
    [[ "$normalized" != *[![:print:]]* ]] || return 1
    [ -z "${tar_seen[$normalized]+set}" ] || return 1
    tar_seen["$normalized"]=1
    if [ "$layout" = bundle ]; then
      case "$normalized" in manifest.env|compose|compose/*|project|project/*) ;; *) return 1 ;; esac
    elif [ "$layout" != folder ]; then
      return 1
    fi
  done <<< "$names"
}

function migrationValidateManifest() {
  local manifest="$1" line name value seen=' ' count=0
  [ -f "$manifest" ] && [ ! -L "$manifest" ] || return 1
  while IFS= read -r line || [ -n "$line" ]; do
    [[ "$line" =~ ^(VDM_MIGRATION_[A-Z_]+)=(.*)$ ]] || return 1
    name="${BASH_REMATCH[1]}"
    decodeEnvValue "${BASH_REMATCH[2]}" value || return 1
    [[ "$seen" != *" $name "* && -n "$value" && "$value" != *$'\n'* && "$value" != *$'\r'* ]] || return 1
    seen+="$name "
    count=$((count + 1))
    case "$name" in
      VDM_MIGRATION_FORMAT) [ "$value" = 1 ] || return 1 ;;
      VDM_MIGRATION_CONTAINER) isValidDomain "$value" || return 1 ;;
      VDM_MIGRATION_KEY|VDM_MIGRATION_ENV_KEY) [[ "$value" =~ ^[A-Za-z]+$ ]] || return 1 ;;
      VDM_MIGRATION_PROJECT_FOLDER) isSafeProjectName "$value" || return 1 ;;
      VDM_MIGRATION_SOURCE_PROJECT_PATH) isSafeMigrationPath "$value" || return 1 ;;
      VDM_MIGRATION_DB_IMAGE) [[ "$value" =~ ^[a-zA-Z0-9._:/-]+@sha256:[a-f0-9]{64}$ ]] || return 1 ;;
      VDM_MIGRATION_ARCH) [[ "$value" =~ ^[a-zA-Z0-9_/-]+$ ]] || return 1 ;;
      VDM_MIGRATION_SECURE) [[ "$value" == true || "$value" == false ]] || return 1 ;;
      *) return 1 ;;
    esac
  done < "$manifest"
  [ "$count" -eq 9 ]
}

# Verify regular files/directories only, including dotfiles, before privileged
# copies. A cold v1 package deliberately refuses symlinks and special files.
function migrationValidateTree() {
  local tree="$1" invalid
  [ -d "$tree" ] && [ ! -L "$tree" ] || return 1
  invalid=$(runPrivileged find "$tree" \( ! -type d ! -type f \) -o \( -type f -links +1 \) 2>/dev/null) || return 1
  [ -z "$invalid" ]
}

# Reject linked ancestors as well as a linked final component.
function migrationPathHasSymlink() {
  local path="$1" prefix='' component link
  [[ "$path" == /* ]] || return 0
  path="${path#/}"
  while [ -n "$path" ]; do
    component="${path%%/*}"
    prefix+="/$component"
    if [ -L "$prefix" ]; then
      case "${OSTYPE:-}:$prefix" in
        darwin*:/tmp|darwin*:/var|darwin*:/etc)
          link=$(readlink "$prefix") || return 0
          [[ "$link" == "private/${prefix#/}" || "$link" == "/private/${prefix#/}" ]] || return 0 ;;
        *) return 0 ;;
      esac
    fi
    [[ "$path" == */* ]] || break
    path="${path#*/}"
  done
  return 1
}

# Extraction never loads the manifest into the caller's environment. The caller
# owns the empty private staging directory and is responsible for its cleanup.
function extractJoomlaMigration() {
  (
  set +x
  local archive="$1" destination="$2" contents mode refs name value
  [ -d "$destination" ] && ! migrationPathHasSymlink "$destination" || return 1
  # MSYS/Git Bash reports synthetic Unix modes; Windows privacy is governed by
  # the account's NTFS access controls rather than those reported mode bits.
  if [ "${OS_NUMBER:-0}" != 3 ]; then
    mode=$(stat -c '%a' "$destination" 2>/dev/null || stat -f '%Lp' "$destination" 2>/dev/null) || return 1
    [ "$mode" = 700 ] || { showError 'Migration extraction requires an empty private directory (mode 700).'; return 1; }
  fi
  contents=$(find "$destination" -mindepth 1 -print -quit 2>/dev/null) || return 1
  [ -z "$contents" ] || return 1
  if ! migrationValidateTar "$archive" bundle; then
    showError 'The migration archive is invalid or contains unsupported paths, links, or file types.'
    return 1
  fi
  if ! runPrivileged tar --numeric-owner --same-permissions --same-owner -xzf "$archive" -C "$destination" >/dev/null 2>&1; then
    showError 'The migration archive could not be extracted.'
    return 1
  fi
  # Do not let archived directory modes expose private Compose/env metadata.
  runPrivileged chmod 700 "$destination" "$destination/compose" || return 1
  runPrivileged chown "$(id -u):$(id -g)" "$destination/manifest.env" "$destination/compose" "$destination/compose/docker-compose.yml" "$destination/compose/.env" || return 1
  chmod 600 "$destination/manifest.env" "$destination/compose/docker-compose.yml" "$destination/compose/.env" || return 1
  if ! migrationValidateManifest "$destination/manifest.env" ||
    [ ! -f "$destination/compose/docker-compose.yml" ] || [ ! -f "$destination/compose/.env" ] ||
    ! runPrivileged test -d "$destination/project/db" || ! runPrivileged test -f "$destination/project/joomla/configuration.php"; then
    showError 'The migration archive is missing required Joomla metadata or project files.'
    return 1
  fi
  refs=$(migrationComposeReferences "$destination/compose/docker-compose.yml") || return 1
  while IFS= read -r name; do
    [ -z "$name" ] || migrationReadEnvValue "$destination/compose/.env" "$name" value || return 1
  done <<< "$refs"
  migrationValidateScopedEnv "$destination/compose/docker-compose.yml" "$destination/compose/.env"
  )
}

# Validate generated short-form bind mounts. Return only compose-relative paths
# to copy; all project binds must remain under the one selected project folder.
# shellcheck disable=SC2016
function migrationComposeLocalFiles() {
  local yml="$1" project="$2" line trimmed volume source target block=false db=false web=false
  while IFS= read -r line || [ -n "$line" ]; do
    [[ "$line" =~ ^[[:space:]]*(#.*)?$ ]] && continue
    if [[ "$line" =~ ^[[:space:]]*(env_file|include|extends|build|configs|secrets): ]] || [[ "$line" =~ ^volumes: ]]; then
      return 1
    fi
    if [[ "$line" =~ ^[[:space:]]{4}volumes:[[:space:]]*$ ]]; then
      block=true
      continue
    fi
    if "$block" && [[ ! "$line" =~ ^[[:space:]]{6} ]]; then block=false; fi
    "$block" || continue
    trimmed="${line#"${line%%[![:space:]]*}"}"
    [[ "$trimmed" == '- '* ]] || return 1
    volume="${trimmed#- }"
    if [[ "$volume" == \"*\" || "$volume" == \'*\' ]]; then volume="${volume:1:${#volume}-2}"; fi
    [[ "$volume" == *:* ]] || return 1
    source="${volume%%:*}"
    target="${volume#*:}"
    [[ "$target" =~ ^/[^:]+(:[a-zA-Z,]+)?$ ]] || return 1
    if [[ "$source" == '${VDM_PROJECT_PATH}/'"$project/"* ]]; then
      source="${source#'${VDM_PROJECT_PATH}/'}"
      case "/$source/" in *'/../'*|*'/./'*|*'//'*) return 1 ;; esac
      [ "$source" != "$project/db" ] || [[ "$target" == /var/lib/mysql || "$target" == /var/lib/mysql:* ]] || return 1
      [ "$source" != "$project/joomla" ] || [[ "$target" == /var/www/html || "$target" == /var/www/html:* ]] || return 1
      if [[ "$target" == /var/lib/mysql || "$target" == /var/lib/mysql:* ]]; then
        [ "$source" = "$project/db" ] && ! "$db" || return 1
        db=true
      elif [[ "$target" == /var/www/html || "$target" == /var/www/html:* ]]; then
        [ "$source" = "$project/joomla" ] && ! "$web" || return 1
        web=true
      fi
    elif [[ "$source" == ./* ]]; then
      source="${source#./}"
      case "/$source/" in *'/../'*|*'/./'*|*'//'*) return 1 ;; esac
      [[ -n "$source" && "$source" != .env && "$source" != docker-compose.yml && "$source" != *'$'* ]] || return 1
      [[ "$target" != /var/lib/mysql* && "$target" != /var/www/html ]] || return 1
      printf '%s\n' "$source"
    else
      return 1
    fi
  done < "$yml"
  "$db" && "$web"
}

function migrationRestartSource() {
  local id state
  [ "$#" -gt 0 ] || return 0
  docker start "$@" >/dev/null 2>&1 || return 1
  for id in "$@"; do
    state=$(docker inspect --type container --format '{{.State.Running}}' "$id" 2>/dev/null) || return 1
    [ "$state" = true ] || return 1
  done
}

# Export is a subshell so EXIT/signal cleanup cannot replace the caller's traps.
# It shares the clone lock, retains exact running container IDs, and restarts
# only those services, even when stopping, copying, or archiving fails.
function exportJoomlaMigration() {
  (
    set +x
    umask 077
    local container="$1" archive="$2" source_dir source_yml source_env references name value project_root project key env_key secure
    local package='' temporary_archive='' clone_lock="${VDM_REPO_PATH}/joomla/.clone.lock" locked=false restart=false result=1
    local locals path actual_image digests db_image='' architecture all_names state id actual_mounts declared_names config_copy=''
    local running_ids=() source_ids=()
    local VDM_SRC_KEY VDM_SRC_ENV_KEY VDM_SRC_PROJECT_FOLDER VDM_SRC_SECURE VDM_SRC_NAMED_VOLUMES VDM_SRC_MAILCATCHER
    trap 'exit 130' INT
    trap 'exit 143' TERM HUP
    trap '
      result=$?
      if "$restart" && [ "${#running_ids[@]}" -gt 0 ]; then
        if ! migrationRestartSource "${running_ids[@]}"; then
          showError "The source containers could not be restarted after migration packaging. Restart the source project before continuing."
          result=1
        fi
      fi
      [ -z "$package" ] || runPrivileged rm -rf -- "$package"
      [ -z "$temporary_archive" ] || rm -f -- "$temporary_archive"
      [ -z "$config_copy" ] || rm -f -- "$config_copy"
      if "$locked"; then rmdir "$clone_lock" || result=1; fi
      exit "$result"
    ' EXIT
    if ! isValidDomain "$container" || [ -e "$archive" ] || [ -L "$archive" ]; then
      showError 'Select a valid source container and a new archive filename.'
      exit 1
    fi
    source_dir="${VDM_REPO_PATH}/joomla/available/${container}"
    source_yml="$source_dir/docker-compose.yml"
    ! migrationPathHasSymlink "$source_yml" && [ -f "$source_yml" ] || exit 1
    getJoomlaComposeIdentity "$source_yml" || { showError 'Migration requires a generated Joomla Compose layout.'; exit 1; }
    "$VDM_SRC_NAMED_VOLUMES" && { showError 'Migration v1 supports project bind mounts; named Docker volumes require a separate migration.'; exit 1; }
    key="$VDM_SRC_KEY" env_key="$VDM_SRC_ENV_KEY" project="$VDM_SRC_PROJECT_FOLDER" secure="$VDM_SRC_SECURE"
    isSafeProjectName "$project" || exit 1
    source_env=$(getContainerEnvFile joomla "$container" available)
    migrationReadEnvValue "$source_env" VDM_PROJECT_PATH project_root || { showError 'The source environment has no valid project path.'; exit 1; }
    isSafeMigrationPath "$project_root" && ! migrationPathHasSymlink "$project_root/$project" || exit 1
    references=$(migrationComposeReferences "$source_yml") || { showError 'The Compose file contains unsupported environment interpolation.'; exit 1; }
    locals=$(migrationComposeLocalFiles "$source_yml" "$project") || { showError 'The Compose file uses unsupported volumes, external paths, or configuration dependencies.'; exit 1; }
    while IFS= read -r name; do
      [ -z "$name" ] || migrationReadEnvValue "$source_env" "$name" value || { showError 'A required Compose environment value is missing or invalid.'; exit 1; }
    done <<< "$references"
    runPrivileged test -d "$project_root/$project/db" && runPrivileged test -f "$project_root/$project/joomla/configuration.php" || exit 1
    config_copy=$(mktemp "${TMPDIR:-/tmp}/octojoom-migration-config.XXXXXX") || exit 1
    runPrivileged cat "$project_root/$project/joomla/configuration.php" > "$config_copy" || exit 1
    value=$(getJoomlaConfigValue "$config_copy" host)
    rm -f -- "$config_copy" || exit 1
    config_copy=''
    [[ "$value" =~ ^mariadb${key}(:[0-9]+)?$ ]] || { showError 'The Joomla configuration uses an external or unexpected database host.'; exit 1; }
    migrationValidateTree "$project_root/$project" || { showError 'Migration v1 cannot package project symlinks, hard links, or special files.'; exit 1; }
    while IFS= read -r path; do
      [ -n "$path" ] || continue
      ! migrationPathHasSymlink "$source_dir/$path" && [ -e "$source_dir/$path" ] || exit 1
      if [ -d "$source_dir/$path" ]; then migrationValidateTree "$source_dir/$path" || exit 1; else [ -f "$source_dir/$path" ] || exit 1; fi
    done <<< "$locals"
    actual_image=$(docker inspect --type container --format '{{.Image}}' "mariadb$key" 2>/dev/null) || {
      showError 'The source database container must exist so its exact image and mounts can be verified. Start the source project once before packaging; its mutable image tag will not be guessed.'
      exit 1
    }
    [[ "$actual_image" =~ ^sha256:[a-f0-9]{64}$ ]] || exit 1
    digests=$(docker image inspect --format '{{range .RepoDigests}}{{println .}}{{end}}' "$actual_image" 2>/dev/null) || exit 1
    while IFS= read -r value; do
      if [[ "$value" =~ ^[a-zA-Z0-9._:/-]+@sha256:[a-f0-9]{64}$ ]]; then db_image="$value"; break; fi
    done <<< "$digests"
    [ -n "$db_image" ] || { showError 'The source database image has no immutable repository digest. Pin or publish its image before migrating database files.'; exit 1; }
    architecture=$(docker image inspect --format '{{.Architecture}}' "$actual_image" 2>/dev/null) || exit 1
    [[ "$architecture" =~ ^[a-zA-Z0-9_/-]+$ ]] || exit 1
    actual_mounts=$(docker inspect --type container --format '{{range .Mounts}}{{printf "%s\t%s\t%s\n" .Type .Source .Destination}}{{end}}' "mariadb$key" 2>/dev/null) || exit 1
    [ "$actual_mounts" = $'bind\t'"$project_root/$project/db"$'\t/var/lib/mysql' ] || { showError 'The database container mounts differ from its Compose project. Reconcile the source configuration before migration.'; exit 1; }
    if ! mkdir "$clone_lock" 2>/dev/null; then showError 'A clone or migration is already using the source project lock.'; exit 1; fi
    locked=true
    package=$(mktemp -d "${TMPDIR:-/tmp}/octojoom-migration-export.XXXXXX") || exit 1
    temporary_archive=$(mktemp "${archive}.partial.XXXXXX") || exit 1
    mkdir "$package/compose" "$package/project" || exit 1
    cp "$source_yml" "$package/compose/docker-compose.yml" || exit 1
    : > "$package/compose/.env"
    while IFS= read -r name; do
      [ -n "$name" ] || continue
      migrationReadEnvValue "$source_env" "$name" value || exit 1
      formatEnvAssignment "$name=\"$value\"" >> "$package/compose/.env" || exit 1
    done <<< "$references"
    while IFS= read -r path; do
      [ -n "$path" ] || continue
      mkdir -p "$package/compose/$(dirname "$path")" || exit 1
      runPrivileged cp -a "$source_dir/$path" "$package/compose/$path" || exit 1
    done <<< "$locals"
    for name in FORMAT CONTAINER KEY ENV_KEY PROJECT_FOLDER SOURCE_PROJECT_PATH DB_IMAGE ARCH SECURE; do
      case "$name" in
        FORMAT) value=1 ;; CONTAINER) value="$container" ;; KEY) value="$key" ;; ENV_KEY) value="$env_key" ;;
        PROJECT_FOLDER) value="$project" ;; SOURCE_PROJECT_PATH) value="$project_root" ;; DB_IMAGE) value="$db_image" ;;
        ARCH) value="$architecture" ;; SECURE) value="$secure" ;;
      esac
      formatEnvAssignment "VDM_MIGRATION_$name=\"$value\"" >> "$package/manifest.env" || exit 1
    done
    migrationValidateManifest "$package/manifest.env" || exit 1
    declared_names=$(sed -nE 's/^[[:space:]]*container_name:[[:space:]]*([A-Za-z][A-Za-z0-9_-]*)[[:space:]]*$/\1/p' "$source_yml")
    printf '%s\n' "$declared_names" | grep -qxF "mariadb$key" || exit 1
    printf '%s\n' "$declared_names" | grep -qxF "joomla$key" || exit 1
    all_names=$(docker ps -a --format '{{.Names}}' 2>/dev/null) || exit 1
    while IFS= read -r name; do
      [[ "$name" =~ ^(mariadb|joomla|phpmyadmin|mailcatcher)${key}$ ]] || exit 1
      if ! printf '%s\n' "$all_names" | grep -qxF "$name"; then
        [ "$name" != "mariadb$key" ] || exit 1
        continue
      fi
      if [ "$name" = "joomla$key" ]; then
        actual_mounts=$(docker inspect --type container --format '{{range .Mounts}}{{printf "%s\t%s\t%s\n" .Type .Source .Destination}}{{end}}' "$name" 2>/dev/null) || exit 1
        printf '%s\n' "$actual_mounts" | grep -qxF $'bind\t'"$project_root/$project/joomla"$'\t/var/www/html' || {
          showError 'The Joomla container mounts differ from its Compose project. Reconcile the source configuration before migration.'
          exit 1
        }
      fi
      state=$(docker inspect --type container --format '{{.Id}} {{.State.Running}}' "$name" 2>/dev/null) || exit 1
      [[ "$state" =~ ^([a-f0-9]{64})\ (true|false)$ ]] || exit 1
      id="${BASH_REMATCH[1]}"
      source_ids+=("$id")
      if [ "${BASH_REMATCH[2]}" = true ]; then running_ids+=("$id"); fi
    done <<< "$declared_names"
    [ "${#source_ids[@]}" -ge 1 ] || exit 1
    if [ "${#running_ids[@]}" -gt 0 ]; then
      restart=true
      docker stop "${running_ids[@]}" >/dev/null 2>&1 || { showError 'The source services could not be stopped cleanly.'; exit 1; }
    fi
    for id in "${source_ids[@]}"; do
      state=$(docker inspect --type container --format '{{.State.Running}}' "$id" 2>/dev/null) || exit 1
      [ "$state" = false ] || { showError 'Source services are still running; database files were not copied.'; exit 1; }
    done
    if ! runPrivileged cp -a "$project_root/$project/." "$package/project/" >/dev/null 2>&1; then
      showError 'The stopped source project could not be copied.'
      exit 1
    fi
    if "$restart"; then
      migrationRestartSource "${running_ids[@]}" || { showError 'The source services could not be restarted.'; exit 1; }
      restart=false
    fi
    migrationValidateTree "$package/project" || exit 1
    if ! runPrivileged tar --numeric-owner -czf - -C "$package" manifest.env compose project > "$temporary_archive" 2>/dev/null; then
      showError 'The migration archive could not be created.'
      exit 1
    fi
    chmod 600 "$temporary_archive" || exit 1
    migrationValidateTar "$temporary_archive" bundle || { showError 'The generated archive contains unsupported filenames or file types.'; exit 1; }
    # Noclobber publication: another process cannot replace an existing archive.
    ln "$temporary_archive" "$archive" || exit 1
    exit 0
  )
}


# Destination migration preparation deliberately keeps host configuration and
# shared environment files unchanged. Only newly reserved project paths publish.
function migrationDestinationAvailable() {
  local key="${1:-}" host="${2:-}" suffix candidate key_status=0
  [[ "$key" =~ ^[A-Za-z]+$ ]] && isValidDomain "$host" || return 1
  [[ "${host%%.*}" =~ ^[A-Za-z]+$ ]] || return 1
  for candidate in "${VDM_PROJECT_PATH}/${key}" "${VDM_REPO_PATH}/joomla/available/${host}" "${VDM_REPO_PATH}/joomla/enabled/${host}"; do
    [ ! -e "$candidate" ] && [ ! -L "$candidate" ] || return 1
  done
  isJoomlaKeyInUse "$key" || key_status=$?
  case "$key_status" in 1) ;; 0) return 1 ;; *) return 2 ;; esac
  for suffix in '' db mail; do
    isJoomlaHostInUse "${host%%.*}${suffix}.${host#*.}" && return 1
  done
  return 0
}

# Compose environment interpolation prefers exported shell variables over its
# env file. Keep the importer variables for path handling, but remove their
# export attribute in the calling subshell so package values are authoritative.
function migrationUnexportComposeReferences() {
  local file="$1" refs name
  refs=$(migrationComposeReferences "$file") || return 1
  while IFS= read -r name; do
    [ -z "$name" ] || export -n "${name?}" || return 1
  done <<< "$refs"
}

function migrationRunCompose() {
  (
    local env_file="$1" compose_file="$2"
    shift 2
    migrationUnexportComposeReferences "$compose_file" || exit 1
    docker compose --env-file "$env_file" --file "$compose_file" "$@"
  )
}

function migrationNormalizeArchitecture() {
  case "${1:-}" in
    x86_64|amd64) printf 'amd64\n' ;;
    aarch64|arm64) printf 'arm64\n' ;;
    armv7l|armv7) printf 'armv7\n' ;;
    *) printf '%s\n' "${1:-}" ;;
  esac
}

# Rewrite generated routing values, preserving unrelated service options and
# user middleware. A source middleware chain retains its non-Octojoom entries.
function migrationRewriteComposeSettings() {
  local file="$1" key="$2" secure="$3" resolver="$4" image="$5" network="$6" temporary
  [[ "$key" =~ ^[A-Za-z]+$ && "$network" =~ ^[A-Za-z0-9][A-Za-z0-9_.-]*$ ]] || return 1
  [[ "$secure" == true || "$secure" == false ]] || return 1
  [[ "$secure" == false || "$resolver" == vdmresolver || "$resolver" == cfresolver ]] || return 1
  temporary=$(mktemp "${file}.settings.XXXXXX") || return 1
  if ! awk -v key="$key" -v secure="$secure" -v resolver="$resolver" -v image="$image" -v network="$network" '
    function router(line, v) {
      v=line; sub(/^.*traefik.http.routers\./,"",v); sub(/\..*$/,"",v); return v
    }
    function known(v) {return v == "joomla" key || v == "phpmyadmin" key || v == "mailcatcher" key}
    function label(v, property, value) {print "      - \"traefik.http.routers." v "." property "=" value "\""}
    NR==FNR {
      if ($0 ~ /traefik.http.routers\..*\.middlewares=/ && known(router($0))) {
        v=router($0); value=$0; sub(/^.*\.middlewares=/,"",value); sub(/"[[:space:]]*$/,"",value)
        n=split(value,parts,","); extra[v]=""
        for(i=1;i<=n;i++) if(parts[i]!="cloudflare" && parts[i]!="joomla-security" && parts[i]!="") extra[v]=extra[v] (extra[v]!=""?",":"") parts[i]
      }
      next
    }
    /^services:[[:space:]]*$/ {services=1; networks=0}
    /^networks:[[:space:]]*$/ {services=0; networks=1; traefik=0}
    /^[A-Za-z_]/ && !/^services:/ && !/^networks:/ {services=0; networks=0}
    services && /^  [A-Za-z][A-Za-z0-9_-]*:[[:space:]]*$/ {service=$0; sub(/^  /,"",service); sub(/:[[:space:]]*$/,"",service)}
    services && service == "mariadb" key && /^    image:/ {print "    image: " image; images++; next}
    networks && /^  traefik:[[:space:]]*$/ {traefik=1}
    networks && /^  [^ ]/ && !/^  traefik:/ {traefik=0}
    networks && traefik && /^    name:/ {print "    name: " network; names++; next}
    /^[[:space:]]*#/ {print; next}
    /traefik.http.services\..*\.loadbalancer.server.port=/ {
      v=$0; sub(/^.*traefik.http.services\./,"",v); sub(/\..*$/,"",v)
      if(known(v)) next
    }
    /traefik.http.routers\./ {
      v=router($0)
      if(known(v) && $0 ~ /\.(entrypoints|tls|tls.certresolver|service|middlewares)=/) next
      if(known(v) && $0 ~ /\.rule=Host\(/) {
        print
        label(v,"entrypoints",secure=="true"?"websecure":"web")
        label(v,"service",v)
        print "      - \"traefik.http.services." v ".loadbalancer.server.port=" (v=="mailcatcher" key?1080:80) "\""
        middle=extra[v]
        if(secure=="true") {
          label(v,"tls.certresolver",resolver)
          middle=(resolver=="cfresolver"?"cloudflare,":"") "joomla-security" (middle!=""?"," middle:"")
        }
        if(middle!="") label(v,"middlewares",middle)
        next
      }
    }
    {print}
    END {if(images!=1 || names!=1) exit 1}
  ' "$file" "$file" > "$temporary" || ! chmod 600 "$temporary" || ! mv -f "$temporary" "$file"; then
    rm -f "$temporary"
    return 1
  fi
}

# Only the standard literal properties emitted by Joomla are changed. A custom
# expression or duplicate property is rejected instead of executing PHP.
function migrationPatchJoomlaSettings() {
  local file="$1" old_key="$2" new_key="$3" host="$4" secure="$5" temporary working old_live old_cookie scheme force
  working=$(mktemp) || return 1
  if ! runPrivileged cat "$file" > "$working" || ! cloneJoomlaConfiguration "$working" "$old_key" "$new_key"; then
    rm -f "$working"
    return 1
  fi
  old_live=$(getJoomlaConfigValue "$working" live_site) || { rm -f "$working"; return 1; }
  old_cookie=$(getJoomlaConfigValue "$working" cookie_domain) || { rm -f "$working"; return 1; }
  scheme=http; force=0
  # HTTPS routing belongs to destination Traefik. Preserve existing application
  # SSL/proxy behavior; enabling force_ssl on a development site could loop.
  if [ "$secure" = true ]; then scheme=https; force=preserve; fi
  temporary=$(mktemp) || { rm -f "$working"; return 1; }
  if ! awk -v host="$host" -v scheme="$scheme" -v force="$force" -v live="$old_live" -v cookie="$old_cookie" '
    /^[[:space:]]*public[[:space:]]+\$force_ssl[[:space:]]*=/ {
      if($0 !~ /^[[:space:]]*public[[:space:]]+\$force_ssl[[:space:]]*=[[:space:]]*[0-2];[[:space:]]*$/ || ++seenforce>1) exit 1
      if(force=="preserve") print; else print "\tpublic $force_ssl = " force ";"; next
    }
    /^[[:space:]]*public[[:space:]]+\$(live_site|cookie_domain)[[:space:]]*=/ {
      name=$0; sub(/^.*\$/,"",name); sub(/[[:space:]]*=.*$/,"",name)
      if($0 !~ /^[[:space:]]*public[[:space:]]+\$(live_site|cookie_domain)[[:space:]]*=[[:space:]]*\047[^\047]*\047;[[:space:]]*$/ || ++seen[name]>1) exit 1
      value=(name=="live_site"?(live!=""?scheme "://" host:""):(cookie!=""?host:""))
      print "\tpublic $" name " = \047" value "\047;"; next
    }
    {print}
    END {if(seenforce!=1) exit 1}
  ' "$working" > "$temporary" || ! runPrivileged tee "$file" < "$temporary" >/dev/null; then
    rm -f "$temporary" "$working"
    return 1
  fi
  rm -f "$temporary" "$working"
}

# Operate on an extracted private package, never on a live destination. The
# environment file remains project-scoped and database credentials are unchanged.
function realignJoomlaMigration() {
  set +x
  local package="$1" key="$2" env_key="$3" host="$4" secure="$5" resolver="${6:-}" puid="${7:-}" pgid="${8:-}"
  local old_key old_env old_container old_folder db_image source_arch manifest="$1/manifest.env" env="$1/compose/.env" compose="$1/compose/docker-compose.yml"
  local temporary variable value suffix network="${VDM_TRAEFIK_GATEWAY:-traefik_webgateway}"
  [[ "$key" =~ ^[A-Za-z]+$ && "$env_key" =~ ^[A-Z]+$ && "${host%%.*}" =~ ^[A-Za-z]+$ ]] && isValidDomain "$host" || return 1
  [[ "$secure" == true || "$secure" == false ]] || return 1
  [[ "$secure" == false || "$resolver" == vdmresolver || "$resolver" == cfresolver ]] || return 1
  if [ -n "$puid$pgid" ]; then [[ "$puid" =~ ^[0-9]+$ && "$pgid" =~ ^[0-9]+$ ]] || return 1; fi
  migrationValidateManifest "$manifest" || return 1
  migrationReadEnvValue "$manifest" VDM_MIGRATION_KEY old_key || return 1
  migrationReadEnvValue "$manifest" VDM_MIGRATION_ENV_KEY old_env || return 1
  migrationReadEnvValue "$manifest" VDM_MIGRATION_CONTAINER old_container || return 1
  migrationReadEnvValue "$manifest" VDM_MIGRATION_PROJECT_FOLDER old_folder || return 1
  migrationReadEnvValue "$manifest" VDM_MIGRATION_DB_IMAGE db_image || return 1
  temporary=$(mktemp "${compose}.identity.XXXXXX") || return 1
  if ! rewriteJoomlaComposeIdentity "$compose" "$temporary" "$old_key" "$key" "$old_env" "$env_key" \
      "${old_container%%.*}" "${host%%.*}" "${old_container#*.}" "${host#*.}" "$old_folder" ||
      ! chmod 600 "$temporary" || ! mv -f "$temporary" "$compose"; then
    rm -f "$temporary"
    return 1
  fi
  migrationRewriteComposeSettings "$compose" "$key" "$secure" "$resolver" "$db_image" "$network" || return 1
  temporary=$(mktemp "${env}.identity.XXXXXX") || return 1
  if ! cloneContainerEnvFile "$env" "$temporary" "$old_env" "$env_key" || ! mv -f "$temporary" "$env"; then
    rm -f "$temporary"
    return 1
  fi
  writeEnvVariable "$env" "VDM_PROJECT_PATH=\"${VDM_PROJECT_PATH}\"" true || return 1
  for suffix in DB DB_USER DB_PASS DB_ROOT; do
    migrationReadEnvValue "$env" "VDM_${env_key}_${suffix}" value || return 1
    [ -n "$value" ] || return 1
  done
  # UID/GID changes apply only when the source image already used these settings.
  if [ -n "$puid" ]; then
    for suffix in PUID PGID; do
      variable="VDM_${env_key}_${suffix}"
      if grep -qF "\${${variable}}" "$compose"; then
        if [ "$suffix" = PUID ]; then value="$puid"; else value="$pgid"; fi
        writeEnvVariable "$env" "${variable}=\"#${value}\"" true || return 1
      fi
    done
    runPrivileged chown -R "${puid}:${pgid}" "${package}/project/joomla" || return 1
    for variable in php.ini entrypoint.sh; do
      [ ! -f "${package}/project/${variable}" ] || runPrivileged chown "${puid}:${pgid}" "${package}/project/${variable}" || return 1
    done
  fi
  migrationPatchJoomlaSettings "${package}/project/joomla/configuration.php" "$old_key" "$key" "$host" "$secure" || return 1
  migrationValidateScopedEnv "$compose" "$env" || return 1
  # Quiet validation prevents resolved credentials from reaching progress/logs.
  migrationRunCompose "$env" "$compose" config -q >/dev/null 2>&1 || return 1
}

# Validate destination capabilities without changing the host proxy. A nonzero
# result prevents activation but does not discard a successfully prepared site.
function migrationDestinationReady() {
  local secure="$1" resolver="${2:-}" command labels
  docker network inspect "${VDM_TRAEFIK_GATEWAY:-traefik_webgateway}" >/dev/null 2>&1 || {
    printf 'The destination Traefik network is not available.\n'; return 1;
  }
  [ "$(docker inspect --format '{{.State.Running}}' traefik 2>/dev/null)" = true ] || {
    printf 'The destination Traefik container is not running.\n'; return 1;
  }
  command=$(docker inspect --format '{{range .Config.Cmd}}{{println .}}{{end}}' traefik 2>/dev/null) || return 1
  labels=$(docker inspect --format '{{json .Config.Labels}}' traefik 2>/dev/null) || return 1
  if [ "$secure" = true ]; then
    printf '%s\n' "$command" | grep -qF -- "--certificatesresolvers.${resolver}.acme." || {
      printf 'The selected ACME resolver is not configured on destination Traefik.\n'; return 1;
    }
    printf '%s\n' "$labels" | grep -qF 'traefik.http.middlewares.joomla-security.' || {
      printf 'The Joomla security middleware is not configured on destination Traefik.\n'; return 1;
    }
    if [ "$resolver" = cfresolver ]; then
      printf '%s\n' "$labels" | grep -qF 'traefik.http.middlewares.cloudflare.' || {
        printf 'The Cloudflare middleware is not configured on destination Traefik.\n'; return 1;
      }
    fi
  elif printf '%s\n%s\n' "$command" "$labels" | grep -qE '(redirectscheme.scheme[^a-z]+https|entrypoints.web.http.redirections.entrypoint)'; then
    printf 'Destination Traefik redirects HTTP globally; configure an HTTP-compatible host before enabling this development site.\n'
    return 1
  fi
  return 0
}

# Deterministic, non-interactive archive import. The lock also serializes against
# cloning. mkdir reserves each final path, and only those reservations roll back.
function prepareJoomlaMigration() {
  (
    set +x
    umask 077
    local archive="$1" key="$2" env_key="$3" host="$4" secure="$5" resolver="${6:-}" puid="${7:-}" pgid="${8:-}"
    local staging='' source_arch target_arch status=0 published=false project_reserved=false compose_reserved=false
    local VDM_CONTAINER_TYPE=joomla
    local lock="${VDM_REPO_PATH}/joomla/.clone.lock" project="${VDM_PROJECT_PATH}/${key}" destination="${VDM_REPO_PATH}/joomla/available/${host}"
    createPrivateDirectory -p "${VDM_REPO_PATH}/joomla/available" || exit 1
    mkdir "$lock" 2>/dev/null || { showError 'A clone or migration is already running on this destination.'; exit 1; }
    trap 'status=$?; trap - EXIT; if [ "$published" != true ]; then
      if [ "$compose_reserved" = true ]; then runPrivileged rm -rf -- "$destination"; fi
      if [ "$project_reserved" = true ]; then runPrivileged rm -rf -- "$project"; fi
    fi; if [ -n "$staging" ]; then runPrivileged rm -rf -- "$staging"; fi; rmdir "$lock" 2>/dev/null || status=1; exit "$status"' EXIT
    trap 'exit 130' INT
    trap 'exit 143' TERM
    trap 'exit 129' HUP
    migrationDestinationAvailable "$key" "$host" || { showError 'Destination identity is already used, or Docker could not verify its availability.'; exit 1; }
    staging=$(mktemp -d "${VDM_PROJECT_PATH}/.migration.XXXXXX") || exit 1
    extractJoomlaMigration "$archive" "$staging" || { showError 'The migration package could not be safely extracted.'; exit 1; }
    migrationValidateManifest "${staging}/manifest.env" || exit 1
    migrationReadEnvValue "${staging}/manifest.env" VDM_MIGRATION_ARCH source_arch || exit 1
    target_arch=$(docker info --format '{{.Architecture}}' 2>/dev/null) || exit 1
    if [ -z "$target_arch" ] || [ "$(migrationNormalizeArchitecture "$source_arch")" != "$(migrationNormalizeArchitecture "$target_arch")" ]; then
      showError 'The destination architecture differs from the cold database package. Use a logical database migration across architectures.'; exit 1
    fi
    realignJoomlaMigration "$staging" "$key" "$env_key" "$host" "$secure" "$resolver" "$puid" "$pgid" || {
      showError 'The migration configuration could not be validated. No destination project was published.'; exit 1;
    }
    migrationDestinationAvailable "$key" "$host" || exit 1
    mkdir "$project" || exit 1
    project_reserved=true
    mkdir "$destination" || exit 1
    compose_reserved=true
    # The staging tree is on the projects filesystem. Rename the data tree over
    # our empty reservation instead of copying an entire database a second time.
    mkdir "${staging}/publish" || exit 1
    runPrivileged mv "${staging}/project" "${staging}/publish/${key}" || exit 1
    runPrivileged mv "${staging}/publish/${key}" "${VDM_PROJECT_PATH}/" || exit 1
    runPrivileged cp -a "${staging}/compose/." "$destination/" || exit 1
    runPrivileged chown "$(id -u):$(id -g)" "$destination" "$destination/.env" "$destination/docker-compose.yml" || exit 1
    chmod 700 "$destination" || exit 1
    chmod 600 "$destination/.env" "$destination/docker-compose.yml" || exit 1
    published=true
  )
}

function migrationWaitHealthy() {
  local key="$1" timeout="${2:-120}" started=$SECONDS state service complete
  [[ "$timeout" =~ ^[0-9]+$ ]] || return 1
  while [ "$((SECONDS-started))" -lt "$timeout" ]; do
    complete=true
    for service in mariadb joomla; do
      state=$(docker inspect --format '{{if .State.Running}}{{if .State.Health}}{{.State.Health.Status}}{{else}}missing-healthcheck{{end}}{{else}}stopped{{end}}' "${service}${key}" 2>/dev/null) || return 1
      case "$state" in
        healthy) ;;
        starting) complete=false ;;
        *) return 1 ;;
      esac
    done
    "$complete" && return 0
    sleep 2
  done
  return 1
}

# Test the installed application's real database credentials inside its own
# container, then its destination route. The host never receives the password.
function migrationVerifyApplication() {
  local key="$1" host="$2" secure="$3" scheme=http port=80 started=$SECONDS response code redirect current visited hop retry
  docker exec "joomla${key}" php -r 'require "/var/www/html/configuration.php"; $c = new JConfig; $host = explode(":", $c->host, 2); mysqli_report(MYSQLI_REPORT_OFF); $db = @new mysqli($host[0], $c->user, $c->password, $c->db, isset($host[1]) ? (int) $host[1] : 3306); exit($db->connect_errno ? 1 : 0);' >/dev/null 2>&1 || return 1
  if [ "$secure" = true ]; then scheme=https; port=443; fi
  # --resolve checks the destination proxy and certificate even before clients
  # switch DNS. ACME issuance itself still requires valid public DNS/challenges.
  while [ "$((SECONDS-started))" -lt 120 ]; do
    current="${scheme}://${host}/"; visited=$'\n'; retry=false
    for ((hop=0; hop<6; hop++)); do
      [[ "$visited" != *$'\n'"$current"$'\n'* ]] || return 1
      visited+="$current"$'\n'
      if ! response=$(curl --fail --silent --output /dev/null --connect-timeout 5 --max-time 15 \
          --write-out '%{http_code} %{redirect_url}' --resolve "${host}:${port}:127.0.0.1" "$current"); then
        retry=true
        break
      fi
      code="${response%% *}"; redirect="${response#* }"
      [[ "$code" =~ ^2[0-9][0-9]$ ]] && return 0
      [[ "$code" =~ ^3[0-9][0-9]$ && "$redirect" == "${scheme}://${host}/"* ]] || return 1
      current="$redirect"
    done
    "$retry" || return 1
    sleep 2
  done
  return 1
}

function activateJoomlaMigration() {
  (
  local key="$1" host="$2" secure="$3" resolver="${4:-}" destination="${VDM_REPO_PATH}/joomla/available/$2" reason status=0
  local activation_started=false
  [[ "$key" =~ ^[A-Za-z]+$ ]] && isValidDomain "$host" || return 1
  # shellcheck disable=SC2317 # Called indirectly by the signal traps below.
  migrationActivationInterrupted() {
    trap - HUP INT TERM
    if "$activation_started"; then
      if migrationRunCompose "$destination/.env" "$destination/docker-compose.yml" down >/dev/null 2>&1; then
        # Git Bash can represent the enabled link as a directory copy.
        rm -rf -- "${VDM_REPO_PATH}/joomla/enabled/${host}"
      else
        printf '%s\n' 'Migration activation was interrupted and its containers could not be stopped. The enabled marker and prepared files were retained for recovery.' >&2
      fi
    fi
    exit "$1"
  }
  trap 'migrationActivationInterrupted 129' HUP
  trap 'migrationActivationInterrupted 130' INT
  trap 'migrationActivationInterrupted 143' TERM
  reason=$(migrationDestinationReady "$secure" "$resolver") || { showNotice "Project is prepared but remains disabled.\n\n${reason}"; return 1; }
  activation_started=true
  (
    # Existing enable helpers can open dialogs on errors. Their output is kept
    # private here, so suppress their UI and report once after rollback below.
    showError() { :; }
    showNotice() { :; }
    migrationUnexportComposeReferences "$destination/docker-compose.yml" || exit 1
    VDM_CONTAINER_TYPE=joomla VDM_CONTAINER="$host" enableContainer joomla
  ) >/dev/null 2>&1 || status=$?
  if [ "$status" -eq 0 ]; then migrationWaitHealthy "$key" || status=$?; fi
  if [ "$status" -eq 0 ]; then migrationVerifyApplication "$key" "$host" "$secure" || status=$?; fi
  if [ "$status" -ne 0 ]; then
    # Keep recoverable files, but do not leave an unhealthy migration enabled.
    if migrationRunCompose "$destination/.env" "$destination/docker-compose.yml" down >/dev/null 2>&1; then
      rm -rf -- "${VDM_REPO_PATH}/joomla/enabled/${host}"
      showError 'The imported site failed activation, database connectivity, or its HTTP/HTTPS route and certificate check. Its containers were stopped; the prepared files remain available for correction. HTTPS issuance requires the destination DNS and ACME challenge to be ready.'
    else
      showError 'The imported site failed health checks and could not be stopped. Its prepared files remain available; stop the destination containers before retrying.'
    fi
    return 1
  fi
  return 0
  )
}

# User interaction stays on the destination. Opening a package only discloses
# identity metadata; passwords are neither prompted for nor displayed.
function importJoomlaMigration() {
  (
    set +x
    umask 077
    local archive="${1:-}" preview key env_key host secure=false resolver='' puid='' pgid='' reason status=0 member
    # shellcheck disable=SC2034 # Read by the existing container workflow helpers.
    local VDM_CONTAINER_TYPE=joomla
    if [ ! -f "$archive" ] || [ -L "$archive" ]; then showError 'Select a regular migration archive.'; exit 1; fi
    preview=$(mktemp -d "${VDM_PROJECT_PATH}/.migration-preview.XXXXXX") || exit 1
    trap 'runPrivileged rm -rf -- "$preview"' EXIT
    trap 'exit 130' INT
    trap 'exit 143' TERM
    trap 'exit 129' HUP
    migrationValidateTar "$archive" bundle || { showError 'The migration package could not be safely validated.'; exit 1; }
    # Read only metadata for the destination questions. Large project data is
    # extracted once, by prepareJoomlaMigration after the user has chosen a plan.
    for member in manifest.env compose/docker-compose.yml; do
      if [[ "$member" == */* ]]; then mkdir -p "$preview/${member%/*}" || exit 1; fi
      if ! tar -xOzf "$archive" "$member" > "$preview/$member" 2>/dev/null; then
        tar -xOzf "$archive" "./$member" > "$preview/$member" 2>/dev/null || exit 1
      fi
    done
    migrationValidateManifest "$preview/manifest.env" || exit 1
    migrationReadEnvValue "$preview/manifest.env" VDM_MIGRATION_KEY key || exit 1
    migrationReadEnvValue "$preview/manifest.env" VDM_MIGRATION_CONTAINER host || exit 1
    while true; do
      key=$(getInput 'Destination project key (letters only). The source key can be retained when unused.' "$key" 'Migration Project Key') || exit 3
      [[ "$key" =~ ^[A-Za-z]+$ ]] || { showError 'Use letters only for the project key.'; continue; }
      host=$(getInput 'Destination hostname, including subdomain and domain.' "$host" 'Migration Hostname') || exit 3
      if [[ ! "${host%%.*}" =~ ^[A-Za-z]+$ ]] || ! isValidDomain "$host"; then showError 'Enter a valid hostname with an alphabetical subdomain.'; continue; fi
      status=0
      migrationDestinationAvailable "$key" "$host" || status=$?
      [ "$status" -ne 0 ] || break
      [ "$status" -ne 2 ] || { showError 'Docker could not inspect destination containers. Restore Docker access before retrying.'; exit 1; }
      showError 'That key or hostname is already in use.'
    done
    env_key="${key^^}"
    if getInputYesNo 'Enable HTTPS for this destination? A working destination Traefik ACME resolver is required.' 'Migration HTTPS' 10 112 'defaultno'; then
      secure=true
      resolver=vdmresolver
      if getInputYesNo 'Use the destination Cloudflare DNS resolver for this site?' 'Migration Cloudflare' 8 112 'defaultno'; then resolver=cfresolver; fi
    fi
    if grep -qE 'APACHE_RUN_(USER|GROUP)=' "$preview/compose/docker-compose.yml" &&
        getInputYesNo 'Change the Apache user/group IDs and website ownership for this destination?' 'Migration Ownership' 10 112 'defaultno'; then
      puid=$(getInput 'Destination Apache user ID.' "$(id -u)" 'Migration User ID') || exit 1
      pgid=$(getInput 'Destination Apache group ID.' "$(id -g)" 'Migration Group ID') || exit 1
      [[ "$puid" =~ ^[0-9]+$ && "$pgid" =~ ^[0-9]+$ ]] || { showError 'User and group IDs must be numeric.'; exit 1; }
    fi
    if ! getInputYesNo "Prepare ${host} using project key ${key}?\nDatabase name, users, passwords and table prefix will be retained.\nDestination paths, routing and Joomla host settings will be realigned.\nHTTPS: ${secure}. The source is unaffected by destination import." 'Prepare Migration' 14 112 'defaultno'; then exit 3; fi
    # Release the preview before extracting the publication copy; large projects
    # need only one extracted copy plus the final project during publication.
    runPrivileged rm -rf -- "$preview" || exit 1
    preview=''
    trap - EXIT
    prepareJoomlaMigration "$archive" "$key" "$env_key" "$host" "$secure" "$resolver" "$puid" "$pgid" || exit 1
    if reason=$(migrationDestinationReady "$secure" "$resolver"); then
      if getInputYesNo 'The project is prepared. Enable it now and wait for database and Joomla health checks?' 'Enable Migrated Site' 10 112 'defaultno'; then
        activateJoomlaMigration "$key" "$host" "$secure" "$resolver" || exit 1
        showNotice "Migration complete. ${host} is enabled; database connectivity, container health and the destination HTTP/HTTPS route passed."
      else
        showNotice "Migration prepared. ${host} remains disabled in available containers."
      fi
    else
      showNotice "Migration prepared. ${host} remains disabled.\n\n${reason}"
    fi
  )
}


# Migration control messages contain paths and identifiers only. All deployment
# contents travel in one gzip-compressed archive in either direction.
function createMigrationWorkspace() {
  local base="${VDM_SRC_PATH}/migrations"
  [ ! -L "$base" ] || return 1
  createPrivateDirectory -p "$base" || return 1
  chmod 700 "$base" || return 1
  (umask 077; mktemp -d "${base}/migration.XXXXXXXX")
}

function isMigrationWorkspace() {
  local path="${1:-}" base="${VDM_SRC_PATH}/migrations" suffix
  [[ "$path" == "$base"/migration.* ]] || return 1
  suffix="${path#"$base"/migration.}"
  [[ "$suffix" =~ ^[A-Za-z0-9]+$ ]] && [ -d "$path" ] && [ ! -L "$path" ] && [ ! -L "$base" ]
}

function migrationArchiveDigest() {
  local file="$1" digest
  [ -f "$file" ] && [ ! -L "$file" ] || return 1
  if command -v sha256sum >/dev/null 2>&1; then
    digest=$(sha256sum < "$file") || return 1
  else
    digest=$(shasum -a 256 < "$file") || return 1
  fi
  digest="${digest%% *}"
  [[ "$digest" =~ ^[a-fA-F0-9]{64}$ ]] || return 1
  printf '%s\n' "$digest"
}

# Fixed worker API used by a peer's installed Octojoom. Never eval incoming
# arguments or load an archive's environment into the host configuration.
function migrationWorker() {
  (
    set +x
    umask 077
    local action="${1:-}" workspace container path tool
    local VDM_CONTAINER_TYPE=joomla VDM_FORCE=false OS_NUMBER=0
    [ "$#" -gt 0 ] || return 1
    shift
    VDM_HOME_PATH="${OCTOJOOM_HOME:-$HOME}"
    VDM_SRC_PATH="${VDM_HOME_PATH}/.config/octojoom"
    local worker_home="$VDM_HOME_PATH" worker_src="$VDM_SRC_PATH"
    if ! loadEnvFile "${VDM_SRC_PATH}/.env"; then
      printf '%s\n' 'The remote Octojoom configuration is unavailable.' >&2
      return 1
    fi
    VDM_HOME_PATH="$worker_home"
    VDM_SRC_PATH="$worker_src"
    case "$OSTYPE" in linux-gnu*) OS_NUMBER=1 ;; darwin*) OS_NUMBER=2 ;; msys*|cygwin*) OS_NUMBER=3 ;; esac
    export LC_ALL=C
    if [ ! -d "${VDM_REPO_PATH:-}" ] || [ ! -d "${VDM_PROJECT_PATH:-}" ]; then
      printf '%s\n' 'Initialize Octojoom repository and project paths before migration.' >&2
      return 1
    fi
    # Noninteractive protocol operations must not invoke whiptail on failure.
    if [ "$action" != import ]; then
      # shellcheck disable=SC2317
      showError() { printf '%s\n' "$1" >&2; }
      # shellcheck disable=SC2317
      showNotice() { printf '%s\n' "$1" >&2; }
    fi
    case "$action" in
      capabilities)
        [ "$#" -eq 0 ] || return 1
        for tool in tar gzip rsync docker; do
          command -v "$tool" >/dev/null 2>&1 || {
            printf 'Migration requires %s on this host.\n' "$tool" >&2
            return 1
          }
        done
        command -v sha256sum >/dev/null 2>&1 || command -v shasum >/dev/null 2>&1 || return 1
        printf '%s\n' octojoom-migration-v1
        ;;
      list)
        [ "$#" -eq 0 ] || return 1
        for path in "${VDM_REPO_PATH}/joomla/available/"*/docker-compose.yml; do
          [ -f "$path" ] || continue
          container="${path%/docker-compose.yml}"
          container="${container##*/}"
          isValidDomain "$container" && printf '%s\n' "$container"
        done
        return 0
        ;;
      receive)
        [ "$#" -eq 0 ] || return 1
        createMigrationWorkspace
        ;;
      export)
        [ "$#" -eq 1 ] && isValidDomain "$1" || return 1
        workspace=$(createMigrationWorkspace) || return 1
        if ! exportJoomlaMigration "$1" "${workspace}/package.tar.gz" >&2; then
          rm -rf -- "$workspace"
          return 1
        fi
        printf '%s\n' "$workspace"
        ;;
      export-to)
        [ "$#" -eq 2 ] && isValidDomain "$1" && isMigrationWorkspace "$2" || return 1
        exportJoomlaMigration "$1" "${2}/package.tar.gz"
        ;;
      digest|import)
        [ "$#" -eq 1 ] || return 1
        workspace="${1%/package.tar.gz}"
        [ "$1" = "${workspace}/package.tar.gz" ] && isMigrationWorkspace "$workspace" || return 1
        [ -f "$1" ] && [ ! -L "$1" ] || return 1
        if [ "$action" = digest ]; then
          migrationArchiveDigest "$1"
        else
          command -v whiptail >/dev/null 2>&1 || {
            printf '%s\n' 'Destination realignment requires whiptail.' >&2
            return 1
          }
          importJoomlaMigration "$1"
        fi
        ;;
      cleanup)
        [ "$#" -eq 1 ] && isMigrationWorkspace "$1" || return 1
        rm -rf -- "$1"
        ;;
      *) printf '%s\n' 'Unsupported migration worker operation.' >&2; return 1 ;;
    esac
  )
}

# Quote each argument once for the remote POSIX shell. The program is the
# destination's installed copy; archives never carry executable migration code.
function remoteMigrationWorker() {
  local remote="$1" tty="$2" command argument
  shift 2
  # shellcheck disable=SC2016
  command='if command -v octojoom >/dev/null 2>&1; then octojoom_program=$(command -v octojoom); elif [ -f "$HOME/octojoom" ]; then octojoom_program="$HOME/octojoom"; else printf "%s\n" "Octojoom is not installed on this host." >&2; exit 1; fi; if ! grep -q "^function migrationWorker() {" "$octojoom_program"; then printf "%s\n" "Update Octojoom on the remote host before migrating." >&2; exit 1; fi; exec bash "$octojoom_program" --migration-worker'
  for argument in "$@"; do
    command+=" $(quoteRemoteArgument "$argument")"
  done
  if [ "$tty" = true ]; then
    ssh -t -- "$remote" "$command"
  else
    ssh -- "$remote" "$command"
  fi
}

function isRemoteMigrationWorkspace() {
  local path="${1:-}"
  isSafeMigrationPath "$path" && [[ "$path" =~ /migrations/migration\.[A-Za-z0-9]+$ ]]
}

function selectRemoteMigrationProject() {
  local remote="$1" projects project selected
  local -a choices=()
  projects=$(remoteMigrationWorker "$remote" false list) || return 1
  while IFS= read -r project; do
    [ -n "$project" ] || continue
    isValidDomain "$project" || return 1
    choices+=("$project" "$project")
  done <<< "$projects"
  [ "${#choices[@]}" -gt 0 ] || {
    showError 'No available Joomla projects were found on the source host.'
    return 1
  }
  selected=$(whiptail --title 'Source Joomla project' --menu \
    'Select the remote project to package and pull.' 20 112 10 "${choices[@]}" \
    --backtitle "$BACK_TITLE" --notags 3>&1 1>&2 2>&3) || return 1
  printf '%s\n' "$selected"
}

function joomla__TRuST__migrate() {
  (
    set +x
    local direction remote container capabilities local_workspace='' remote_workspace=''
    local local_archive remote_archive local_digest remote_digest migration_status=0
    direction=$(getMigrationType) || return 1
    [[ "$direction" == push || "$direction" == pull ]] || return 1
    remote=$(getRemoteSystem) || return 1
    if [ -z "$remote" ] || [ "$remote" = none_selected ]; then
      showNotice 'Migration cancelled: no remote host was selected.'
      return 0
    fi
    capabilities=$(remoteMigrationWorker "$remote" false capabilities) || {
      showError 'The remote host is not ready for complete project migration. Update Octojoom on both hosts and verify SSH, Docker, tar and rsync access.'
      return 1
    }
    if [ "$capabilities" != octojoom-migration-v1 ]; then
      showError 'The remote Octojoom migration protocol is incompatible. Update both installations before migrating.'
      return 1
    fi
    if [ "$direction" = push ]; then
      container=$(getSelectedDirectory 'Select the complete Joomla project to package and push.' \
        "${VDM_REPO_PATH}/joomla/available/" '' 'Migrate Joomla project') || return 0
    else
      container=$(selectRemoteMigrationProject "$remote") || return 1
    fi
    [ -n "$container" ] || return 0
    isValidDomain "$container" || return 1
    getInputYesNo "Package (${container}) and ${direction} it through (${remote})?\n\nThe source services will be stopped briefly to take a consistent copy, then restarted. Compose, project-specific environment values and project files travel together in one compressed archive. Destination choices are made on the destination host. The source is retained." \
      'Migrate complete Joomla project' 17 112 || return 0
    local_workspace=$(createMigrationWorkspace) || return 1
    local_archive="${local_workspace}/package.tar.gz"
    if [ "$direction" = push ]; then
      exportJoomlaMigration "$container" "$local_archive" || {
        rm -rf -- "$local_workspace"
        return 1
      }
      remote_workspace=$(remoteMigrationWorker "$remote" false receive) || migration_status=1
    else
      remote_workspace=$(remoteMigrationWorker "$remote" false receive) || migration_status=1
    fi
    if [ "$migration_status" -ne 0 ] || ! isRemoteMigrationWorkspace "$remote_workspace"; then
      showError "Could not prepare the migration archive workspace. Any completed local archive is retained at ${local_archive}."
      return 1
    fi
    remote_archive="${remote_workspace}/package.tar.gz"
    if [ "$direction" = pull ]; then
      # Keep source packaging interactive for ordinary sudo authentication, but
      # keep protocol path discovery separate from terminal output.
      remoteMigrationWorker "$remote" true export-to "$container" "$remote_workspace" || {
        showError "Source packaging failed. The remote recovery workspace is ${remote}:${remote_workspace}."
        return 1
      }
    fi
    if [ "$direction" = push ]; then
      rsync -az --protect-args -- "$local_archive" "${remote}:${remote_archive}" || migration_status=1
    else
      rsync -az --protect-args -- "${remote}:${remote_archive}" "$local_archive" || migration_status=1
    fi
    if [ "$migration_status" -eq 0 ]; then
      local_digest=$(migrationArchiveDigest "$local_archive") || migration_status=1
      remote_digest=$(remoteMigrationWorker "$remote" false digest "$remote_archive") || migration_status=1
      [[ "$remote_digest" =~ ^[a-fA-F0-9]{64}$ ]] && [ "$local_digest" = "$remote_digest" ] || migration_status=1
    fi
    if [ "$migration_status" -eq 0 ]; then
      if [ "$direction" = push ]; then
        remoteMigrationWorker "$remote" true import "$remote_archive" || migration_status=$?
      else
        importJoomlaMigration "$local_archive" || migration_status=$?
      fi
    fi
    if [ "$migration_status" -eq 3 ]; then
      showNotice "Destination setup was cancelled. The packaged project is retained for a later import:\n${local_archive}\n${remote}:${remote_archive}"
      return 3
    fi
    if [ "$migration_status" -ne 0 ]; then
      showError "Migration did not complete. Recovery archives are retained where available:\nLocal: ${local_archive}\nRemote: ${remote}:${remote_archive}\n\nCheck the destination result before retrying. No source project was removed."
      return 1
    fi
    if ! remoteMigrationWorker "$remote" false cleanup "$remote_workspace" || ! rm -rf -- "$local_workspace"; then
      showError "Destination preparation completed, but archive cleanup failed. Remove the private recovery workspaces after checking the destination:\n${local_workspace}\n${remote}:${remote_workspace}"
      return 1
    fi
    showNotice 'The complete project was transferred and prepared on the destination. The source project is retained.'
  )
}


# Parse all options before performing an action. Values passed explicitly on the
# command line override the saved global config loaded later.
function parseCLI() {
  local option variable value
  OCTOJOOM_CLI_ACTION=''
  OCTOJOOM_CLI_KEYS=()
  OCTOJOOM_CLI_VALUES=()
  while [ "$#" -gt 0 ]; do
    option="${1%%=*}"
    variable=''
    case "$1" in
      -h|--help) OCTOJOOM_CLI_ACTION=help; shift; continue ;;
      --update|--uninstall)
        if [ -n "${OCTOJOOM_CLI_ACTION}" ]; then
          echo >&2 "ERROR: Only one action may be requested."
          return 17
        fi
        OCTOJOOM_CLI_ACTION="${1#--}"
        shift
        continue
        ;;
      -y|--yes) VDM_FORCE=true; shift; continue ;;
      --sudo)
        VDM_SUDO_ACCESS=true
        OCTOJOOM_CLI_KEYS+=(VDM_SUDO_ACCESS)
        OCTOJOOM_CLI_VALUES+=(true)
        shift
        continue
        ;;
      --)
        shift
        [ "$#" -eq 0 ] && break
        echo >&2 "ERROR: Unexpected positional argument: $1"
        return 17
        ;;
    esac
    case "${option}" in
      --access-token) variable=VDM_ACCESS_TOKEN ;;
      --type) variable=VDM_CONTAINER_TYPE ;;
      --task) variable=VDM_TASK ;;
      --container) variable=VDM_CONTAINER ;;
      -j|--joomla-version) variable=VDM_JV ;;
      -k|--key) variable=VDM_KEY ;;
      -e|--env-key) variable=VDM_ENV_KEY ;;
      -d|--domain) variable=VDM_DOMAIN ;;
      -s|--sub-domain) variable=VDM_SUBDOMAIN ;;
      -u|--username) variable=VDM_USER_NAME ;;
      --uid) variable=VDM_PUID ;;
      --gid) variable=VDM_PGID ;;
      -p|--port) variable=VDM_PORT ;;
      --ssh-dir) variable=VDM_PUBLIC_KEY_DIR ;;
      -t|--time-zone) variable=VDM_TZ ;;
      *)
        echo >&2 "ERROR: Unknown option or argument: $1"
        return 17
        ;;
    esac
    if [[ "$1" == *=* ]]; then
      value="${1#*=}"
    elif [ "$#" -ge 2 ] && [ -n "$2" ] && [[ "$2" != -* ]]; then
      value="$2"
      shift
    else
      echo >&2 "ERROR: ${option} requires a non-empty option argument."
      return 17
    fi
    if [ -z "${value}" ]; then
      echo >&2 "ERROR: ${option} requires a non-empty option argument."
      return 17
    fi
    printf -v "${variable}" '%s' "${value}"
    OCTOJOOM_CLI_KEYS+=("${variable}")
    OCTOJOOM_CLI_VALUES+=("${value}")
    [ "${variable}" != VDM_DOMAIN ] || VDM_ARG_DOMAIN=true
    shift
  done
  # These per-invocation switches must not come from a saved configuration.
  OCTOJOOM_CLI_KEYS+=(VDM_FORCE VDM_ARG_DOMAIN)
  OCTOJOOM_CLI_VALUES+=("${VDM_FORCE}" "${VDM_ARG_DOMAIN}")
  return 0
}

# defaults
VDM_ARG_DOMAIN=false
VDM_FORCE=false
parseCLI "$@" || exit $?
if [ "${OCTOJOOM_CLI_ACTION}" = help ]; then
  showHelp
  quitProgram
fi

#####################################################################################################################VDM
######################################## CLI PREP


#####################################################################################################################VDM
######################################## SETUP KEY PATHS
# we set a home path based on OS
# (OCTOJOOM_HOME replaces it when set, so the test suite never touches a real home)
VDM_HOME_PATH="${OCTOJOOM_HOME:-}"
[ -n "${VDM_HOME_PATH}" ] || case "$OS_NUMBER" in
  1) # Linux
    VDM_HOME_PATH="/home/${USER}"
    ;;
  2) # macOS
    VDM_HOME_PATH="/Users/${USER}"
    ;;
  3) # Windows (MSYS/Cygwin)
    VDM_HOME_PATH="/c/Users/${USER}"
    ;;
  *)
    echo >&2 "ERROR: Unsupported operating system."
    exit 1
    ;;
esac
# Set the src folder path based on OS
VDM_SRC_PATH="${VDM_HOME_PATH}/.config/octojoom"
# Create the folder if not set
createPrivateDirectory -p "${VDM_SRC_PATH}" || exit 1
# first run switch
VDM_FIRST_RUN=false
OCTOJOOM_RESOLVED_HOME_PATH="${VDM_HOME_PATH}"
OCTOJOOM_RESOLVED_SRC_PATH="${VDM_SRC_PATH}"
# load the globals
if [ -f "${VDM_SRC_PATH}/.env" ]; then
  loadEnvFile "${VDM_SRC_PATH}/.env" || exit 1
fi
VDM_HOME_PATH="${OCTOJOOM_RESOLVED_HOME_PATH}"
VDM_SRC_PATH="${OCTOJOOM_RESOLVED_SRC_PATH}"
VDM_FIRST_RUN=false
unset OCTOJOOM_RESOLVED_HOME_PATH OCTOJOOM_RESOLVED_SRC_PATH
# Restore explicit CLI options after loading saved defaults.
for cli_index in "${!OCTOJOOM_CLI_KEYS[@]}"; do
  printf -v "${OCTOJOOM_CLI_KEYS[cli_index]}" '%s' "${OCTOJOOM_CLI_VALUES[cli_index]}"
done
unset cli_index OCTOJOOM_CLI_KEYS OCTOJOOM_CLI_VALUES
# Resolve targets after loading defaults so a saved domain can accompany a
# CLI subdomain. Tasks operating on all containers need no individual target.
if [ -n "${VDM_CONTAINER}" ]; then
  VDM_CONTAINER_TYPE="${VDM_CONTAINER_TYPE:-joomla}"
  VDM_TASK="${VDM_TASK:-enable}"
fi
if [ -z "${VDM_CONTAINER}" ] && [ -n "${VDM_CONTAINER_TYPE}" ] &&
  [ -n "${VDM_TASK}" ] && [ -n "${VDM_DOMAIN}" ]; then
  sub="${VDM_SUBDOMAIN:-}"
  if [ -z "${sub}" ]; then
    case "${VDM_CONTAINER_TYPE}" in
      portainer) sub=port ;;
      traefik) sub=traefik ;;
      openssh) sub="${VDM_USER_NAME:-}" ;;
    esac
  fi
  [ -z "${sub}" ] || VDM_CONTAINER="${sub}.${VDM_DOMAIN}"
  unset sub
fi
# Update/uninstall use the saved paths but do not initialize new deployments.
case "${OCTOJOOM_CLI_ACTION}" in
  update) runUpdate; exit $? ;;
  uninstall) runUninstall; exit $? ;;
esac
# get repo path where store the container deploy scripts
while [ ${#VDM_REPO_PATH} -le 1 ] || [ ! -d "${VDM_REPO_PATH}" ]; do
  # creat the path if it exist
  if [ ${#VDM_REPO_PATH} -ge 1 ] && (whiptail --yesno "Can we create the ${VDM_REPO_PATH} repository folder" \
    --title "Create the Path" --backtitle "${BACK_TITLE}" 8 112); then
    mkdir -p "${VDM_REPO_PATH}" || exit 1
  else
    # get the value
    VDM_REPO_PATH=$(getInput "Enter the repository path where we can store the containers' docker-composer.yml deployment files." \
      "${VDM_HOME_PATH}/Docker" 'Enter Repository Path') || exit $?
    # keep asking if empty or does exist
    if [ ${#VDM_REPO_PATH} -ge 1 ] && [ ! -d "${VDM_REPO_PATH}" ] && (whiptail --yesno "Can we create the ${VDM_REPO_PATH} repository folder" \
      --title "Create the Path" --backtitle "${BACK_TITLE}" 8 112); then
      mkdir -p "${VDM_REPO_PATH}" || exit 1
    elif [ ${#VDM_REPO_PATH} -le 1 ]; then
      showError "You must set a repository path where we can store the containers' docker-composer.yml deployment files."
    fi
  fi
  # trip switch of first run
  VDM_FIRST_RUN=true
done
# add this value if not set variable
setEnvVariable "VDM_REPO_PATH=\"${VDM_REPO_PATH}\"" || exit $?
# get repo path where store the container deploy scripts
while [ ${#VDM_PROJECT_PATH} -le 1 ] || [ ! -d "${VDM_PROJECT_PATH}" ]; do
  # create the path if it exist
  if [ ${#VDM_PROJECT_PATH} -ge 1 ] && (whiptail --yesno "Can we create the ${VDM_PROJECT_PATH} projects' folder" \
    --title "Create the Path" --backtitle "${BACK_TITLE}" 8 112); then
    mkdir -p "${VDM_PROJECT_PATH}" || exit 1
  else
    # get the value
    VDM_PROJECT_PATH=$(getInput "Enter the projects' path where we can store the containers' persistent volumes." \
      "${VDM_HOME_PATH}/Projects" "Enter Projects' Path") || exit $?
    # keep asking if empty or does exist
    if [ ${#VDM_PROJECT_PATH} -ge 1 ] && [ ! -d "${VDM_PROJECT_PATH}" ] && (whiptail --yesno "Can we create the ${VDM_PROJECT_PATH} projects folder" \
      --title "Create the Path" --backtitle "${BACK_TITLE}" 8 112); then
      mkdir -p "${VDM_PROJECT_PATH}" || exit 1
    elif [ ${#VDM_PROJECT_PATH} -le 1 ]; then
      showError "You must set a projects' path where we can store the containers' persistent volumes."
    fi
  fi
  # trip switch of first run
  VDM_FIRST_RUN=true
done
# add this value if not set variable
setEnvVariable "VDM_PROJECT_PATH=\"${VDM_PROJECT_PATH}\"" || exit $?
# set these globally
export VDM_REPO_PATH
export VDM_PROJECT_PATH
# if this is the first run we should setup traefik
$VDM_FIRST_RUN && {
  # set traefik as the container type
  : "${VDM_CONTAINER_TYPE:=traefik}"
  # and enable it
  : "${VDM_TASK:=setup}"
  # first setup the network
  setNetworks || exit $?
  # trigger main
  main || exit $?
  # clear it again
  VDM_CONTAINER_TYPE=''
  VDM_TASK=''
}

#####################################################################################################################VDM
######################################## MAIN ┬┴┬┴┤(･_├┬┴┬┴
main
