#! /bin/bash

# Program name
PROGRAM_NAME="Octojpack"
PROGRAM_CODE="octojpack"
PROGRAM_VERSION="1.4.0"
PROGRAM_V="1.4"
PROGRAM_URL="https://git.vdm.dev/octoleo/${PROGRAM_CODE}"

# Do some prep work
command -v git >/dev/null 2>&1 || {
  echo >&2 "[error] We require git for $PROGRAM_NAME v${PROGRAM_V} to work, but it's not installed.  Aborting."
  exit 1
}
command -v curl >/dev/null 2>&1 || {
  echo >&2 "[error] We require curl for $PROGRAM_NAME v${PROGRAM_V} to work, but it's not installed.  Aborting."
  exit 1
}
command -v jq >/dev/null 2>&1 || {
  echo >&2 "[error] We require jq for $PROGRAM_NAME v${PROGRAM_V} to work, but it's not installed.  Aborting."
  exit 1
}
command -v unzip >/dev/null 2>&1 || {
  echo >&2 "[error] We require unzip for $PROGRAM_NAME v${PROGRAM_V} to work, but it's not installed.  Aborting."
  exit 1
}

# make sure we have a user name (CI containers do not always set USER)
USER="${USER:-$(id -un 2>/dev/null || echo "${PROGRAM_CODE}")}"

# the language strings of the packager language (used to resolve the package name and description)
declare -gA VDM_LANG_STRINGS=()
# the options given on the command line (they take precedence over the env files)
declare -ga CLI_OPTIONS=()

# main function ˘Ô≈ôﺣ
function main() {
  # check if we have project overrides for the environment variables
  # shellcheck disable=SC2015
  [ -f "$VDM_PACKAGE_CONF_FILE" ] && getProjectEnvironment || {
    echo >&2 "[error] We require config file with correct packaging details for $PROGRAM_NAME v${PROGRAM_V} to work, but it's not found in/at $VDM_PACKAGE_CONF_FILE.  Aborting."
    clearMainEnv
    exit 1
  }
  # get the package details
  getPackageDetails || {
    echo >&2 "[error] We require config file with correct packaging details for $PROGRAM_NAME v${PROGRAM_V} to work, but it's not found in/at $VDM_PACKAGE_CONF_FILE.  Aborting."
    clearMainEnv
    exit 1
  }
  # get destination details (only required when we push to the git repository)
  getRepositoryDetails || {
    if _is_true "${VDM_PACKAGE_PUSH}"; then
      echo >&2 "[error] We require config file with correct destination repository details for $PROGRAM_NAME v${PROGRAM_V} to work, but it's not found in/at $VDM_PACKAGE_CONF_FILE.  Aborting."
      clearMainEnv
      exit 1
    fi
    _echo "[info] No repository details found (push is disabled, so we continue)..."
  }
  # build the project package path
  setPackageDir || {
    echo >&2 "[error] We could not set the package directories for ${VDM_PACKAGE_OWNER}/${VDM_PACKAGE_REPO}.  Aborting."
    clearMainEnv
    exit 1
  }
  # set the files
  setFiles || {
    echo >&2 "[error] We could not find any files for ${VDM_PACKAGE_OWNER}/${VDM_PACKAGE_REPO} package.  Aborting."
    clearMainEnv
    exit 1
  }
  # set languages
  setLanguages
  # set the package XML
  setPackageXml
  # set the readme
  setReadMe
  # set the licence file
  setLicenseFile || {
    echo >&2 "[error] We could not set the LICENSE for ${VDM_PACKAGE_OWNER}/${VDM_PACKAGE_REPO}.  Aborting."
    clearMainEnv
    exit 1
  }
  # set the installation file
  setInstallFile || {
    echo >&2 "[error] We could not set the installation script file for ${VDM_PACKAGE_NAME}.  Aborting."
    clearMainEnv
    exit 1
  }
  # build the package zip file (if requested)
  if _is_true "${VDM_PACKAGE_ZIP}"; then
    setPackageZip || {
      echo >&2 "[error] We could not build the package zip file for ${VDM_PACKAGE_NAME}.  Aborting."
      clearMainEnv
      exit 1
    }
  fi
  # get package repository (if requested)
  if _is_true "${VDM_PACKAGE_PUSH}"; then
    setRepository || {
      echo >&2 "[error] We could not set the GIT repository for ${VDM_PACKAGE_OWNER}/${VDM_PACKAGE_REPO}.  Aborting."
      clearMainEnv
      exit 1
    }
  else
    _echo "[info] Skipping the git repository push (push is disabled)..."
  fi
  # write the build results (manifest and outputs)
  setOutputs || {
    echo >&2 "[error] We could not write the build results for ${VDM_PACKAGE_NAME}.  Aborting."
    clearMainEnv
    exit 1
  }
  # remove all files (unless we must keep them)
  if _is_true "${VDM_KEEP_FILES}"; then
    _echo "[info] Keeping the package files in (${VDM_PACKAGE_DIR})..."
  else
    clearFiles
  fi
  # clear main env
  clearMainEnv
  # final message
  _echo "[Success] Package completely updated!"
}

# set the package details
function getPackageDetails() {
  # little information of progress
  _echo "[info] Loading the Package Details..."
  # make configuration globally available
  export VDM_CONFIG_DATA
  # check for errors
  local has_error=false
  # get the global config values if not set
  getConfigValue 'VDM_PACKAGER' '.global.packager' false || VDM_PACKAGER="${PROGRAM_NAME} v${PROGRAM_V}"
  getConfigValue 'VDM_PACKAGER_URL' '.global.packager_url' false || VDM_PACKAGER_URL="${PROGRAM_URL}"
  getConfigValue 'VDM_PACKAGER_LANG' '.global.language' false || VDM_PACKAGER_LANG="en-GB"
  getConfigValue 'VDM_GLOBAL_TOKEN' '.global.token' || has_error=true
  getConfigValue 'VDM_GLOBAL_API' '.global.api' || has_error=true
  getConfigValue 'VDM_GLOBAL_URL' '.global.url' || has_error=true
  # check if we have some errors already
  $has_error && return 13

  # package related details
  getConfigValue 'VDM_PACKAGE_NAME' '.package.package_name' || has_error=true
  getConfigValue 'VDM_CODE_NAME' '.package.code_name' || has_error=true
  getConfigValue 'VDM_PACKAGE_VERSION_ID' '.package.version_id' false
  getConfigValue 'VDM_NAME' '.package.name' || has_error=true
  getConfigValue 'VDM_DESCRIPTION' '.package.description' || has_error=true
  getConfigValue 'VDM_MIN_JOOMLA_VERSION' '.package.min_joomla_version' false || VDM_MIN_JOOMLA_VERSION="3.8"
  getConfigValue 'VDM_MAX_JOOMLA_VERSION' '.package.max_joomla_version' false || unset VDM_MAX_JOOMLA_VERSION
  getConfigValue 'VDM_COPYRIGHT' '.package.copyright' || has_error=true
  getConfigValue 'VDM_COPYRIGHT_YEAR' '.package.copyright_year' || has_error=true
  getConfigValue 'VDM_LICENSE' '.package.license' || has_error=true
  getConfigValue 'VDM_LICENSE_FILE' '.package.license_file' || has_error=true
  getConfigValue 'VDM_INSTALLATION_FILE' '.package.installation_file' false || unset VDM_INSTALLATION_FILE
  getConfigValue 'VDM_AUTHOR' '.package.author' || has_error=true
  getConfigValue 'VDM_AUTHOR_EMAIL' '.package.author_email' || has_error=true
  getConfigValue 'VDM_AUTHOR_URL' '.package.author_url' || has_error=true
  getConfigValue 'VDM_UPDATE_SERVER' '.package.update_servers' false || unset VDM_UPDATE_SERVER
  getConfigValue 'VDM_CHANGELOG_SERVER' '.package.changelog_servers' false || unset VDM_CHANGELOG_SERVER
  # check if we have some errors already
  $has_error && return 13
  # success
  return 0
}

# set the target repository details
function getRepositoryDetails() {
  # make sure we have repository details (in the config, or given via the environment)
  if [[ "${VDM_CONFIG_DATA}" =~ '"repository"' ]] || { [ -n "${VDM_PACKAGE_OWNER}" ] && [ -n "${VDM_PACKAGE_REPO}" ]; }; then
    # little information of progress
    _echo "[info] Loading the Repository Details..."
    # check for errors
    local has_error=false
    # get the global config values if not set
    getConfigValue 'VDM_PACKAGE_OWNER' '.repository.owner' || has_error=true
    getConfigValue 'VDM_PACKAGE_REPO' '.repository.repo' || has_error=true
    getConfigValue 'VDM_PACKAGE_REPO_BRANCH' '.repository.branch' false || VDM_PACKAGE_REPO_BRANCH="default"
    getConfigValue 'VDM_PACKAGE_TOKEN_NAME' '.repository.token_name' false || VDM_PACKAGE_TOKEN_NAME="VDM_GLOBAL_TOKEN"
    getConfigValue 'VDM_PACKAGE_URL_NAME' '.repository.url_name' false || VDM_PACKAGE_URL_NAME="VDM_GLOBAL_URL"
    getConfigValue 'VDM_PACKAGE_API_NAME' '.repository.api_name' false || VDM_PACKAGE_API_NAME="VDM_GLOBAL_API"
    # check if we have some errors already
    $has_error && return 17
    # make sure the names are safe to use in paths and git urls
    if ! _valid_name "${VDM_PACKAGE_OWNER}" || ! _valid_name "${VDM_PACKAGE_REPO}"; then
      echo >&2 "[error] The repository (${VDM_PACKAGE_OWNER}/${VDM_PACKAGE_REPO}) has an invalid owner or repository name."
      return 17
    fi
    # set the package (api/url/toke)
    VDM_PACKAGE_TOKEN=${!VDM_PACKAGE_TOKEN_NAME}
    VDM_PACKAGE_URL=${!VDM_PACKAGE_URL_NAME}
    VDM_PACKAGE_API=${!VDM_PACKAGE_API_NAME}
    # make globally available
    export VDM_PACKAGE_REPO_BRANCH
    export VDM_PACKAGE_TOKEN
    export VDM_PACKAGE_URL
    export VDM_PACKAGE_API
    # success
    return 0
  else
    # failed
    return 17
  fi
}

# clear the main environment variables
function clearMainEnv() {
  # clear all exported package details
  # SET IN: getRepositoryDetails
  unset VDM_PACKAGE_OWNER
  unset VDM_PACKAGE_REPO
  unset VDM_PACKAGE_REPO_BRANCH
  unset VDM_PACKAGE_TOKEN_NAME
  unset VDM_PACKAGE_TOKEN
  unset VDM_PACKAGE_API_NAME
  unset VDM_PACKAGE_API
  unset VDM_PACKAGE_URL_NAME
  unset VDM_PACKAGE_URL
  # SET IN: setPackageDir
  unset VDM_PACKAGE_DIR
  unset VDM_PACKAGE_GIT_DIR
  unset VDM_PACKAGE_SRC_DIR
  unset VDM_PACKAGE_LANG_DIR
  unset VDM_PACKAGE_XML
  unset VDM_FILES_XML
  unset VDM_LANGUAGES_XML
  unset VDM_README_MD
  unset VDM_INSTALL_PHP
  unset VDM_FILES_JSON
  # SET IN: setPackageZip
  unset VDM_PACKAGE_ZIP_PATH
  unset VDM_PACKAGE_ZIP_SHA256
  unset VDM_PACKAGE_ZIP_SHA256_FILE
  # SET IN: setOutputs
  unset VDM_PACKAGE_MANIFEST
  # SET IN: setRepository
  unset VDM_REPOSITORY_STATUS
  # SET IN: getPackageDetails
  unset VDM_CONFIG_DATA
  unset VDM_PACKAGER
  unset VDM_PACKAGER_URL
  unset VDM_GLOBAL_TOKEN
  unset VDM_GLOBAL_API
  unset VDM_PACKAGE_NAME
  unset VDM_CODE_NAME
  unset VDM_PACKAGE_VERSION
  unset VDM_PACKAGE_VERSION_ID
  unset VDM_NAME
  unset VDM_DESCRIPTION
  unset VDM_MIN_JOOMLA_VERSION
  unset VDM_MAX_JOOMLA_VERSION
  unset VDM_COPYRIGHT
  unset VDM_COPYRIGHT_YEAR
  unset VDM_LICENSE
  unset VDM_LICENSE_FILE
  unset VDM_LICENSE_FILE_PATH
  unset VDM_INSTALLATION_FILE
  unset VDM_AUTHOR
  unset VDM_AUTHOR_EMAIL
  unset VDM_AUTHOR_URL
  unset VDM_UPDATE_SERVER
  unset VDM_CHANGELOG_SERVER
  # SET IN: callGiteaAPI
  unset VDM_API_BUCKET
}

# clear all this projects files
function clearFiles() {
  # always remove files
  rm -fr "${VDM_PACKAGE_DIR:?}"
  [ -n "${VDM_PACKAGE_REPO}" ] && rm -fr "${VDM_PACKAGE_GIT_DIR:?}/${VDM_PACKAGE_REPO}"
  [ -f "${VDM_FILES_JSON}" ] && rm -f "${VDM_FILES_JSON}"
  # success
  return 0
}

# get value from config
function getConfigValue() {
  # with config values we only try to load it
  # if it is not already set
  # so if we find that it is set
  # we're done search
  [ -n "${!1}" ] && return 0
  # get what we can from the config if not already set in the .env file
  # so to set the value globally use the .env option
  # to set per project use the config file of the project
  setValueFromJson "$1" "$2" "$VDM_CONFIG_DATA" || {
    # give little heads-up if not blocked
    "${3:-true}" && echo >&2 "[error] We require ($2) for $PROGRAM_NAME v${PROGRAM_V} to work, but it's not found in $VDM_PACKAGE_CONF_FILE."
    # we had no success
    return 19
  }
  # success
  return 0
}

# Set value from JSON
function setValueFromJson() {
    local target_var="$1"
    local value

    value=$(getValueFromJson "$2" "$3") || {
        return 19
    }

    # Safely use eval to dynamically set the value
    declare -g "$target_var"="$value"
}

# Get value from JSON
function getValueFromJson() {
    local json_key="$1"
    local json_data="$2"
    local value

    # Check if the necessary parameters are provided
    if [[ -z "$json_key" ]]; then
        # [error] Missing required key parameter.
        return 19
    fi

    if [[ -z "$json_data" ]]; then
        # [error] JSON data is empty.
        return 19
    fi

    # Attempt to extract the value using jq
    if ! value=$(echo "$json_data" | jq -r "$json_key"); then
        # [error] Failed to parse JSON data.
        return 19
    fi

    # Check if the value is 'null' or empty
    if [[ "$value" == "null" || -z "$value" ]]; then
        # [error] Key not found or null value.
        return 19
    fi

    # Safely return the value
    echo "$value"
}

# set the Package Path
function setPackageDir() {
  # little information of progress
  _echo "[info] Setting the Package Directories..."
  # the package folder name (falls back to the package name when no repository is set)
  local package_folder
  package_folder="$(_safe_name "${VDM_PACKAGE_REPO:-${VDM_PACKAGE_NAME,,}}")" || return 12
  # the full project path
  VDM_PACKAGE_DIR="${VDM_MAIN_DIR:?}/${package_folder:?}"
  VDM_PACKAGE_GIT_DIR="${VDM_MAIN_DIR}/git"
  VDM_PACKAGE_SRC_DIR="${VDM_PACKAGE_DIR}/src"
  # always remove previous files (if found)
  rm -fr "${VDM_PACKAGE_DIR:?}"
  [ -n "${VDM_PACKAGE_REPO}" ] && rm -fr "${VDM_PACKAGE_GIT_DIR:?}/${VDM_PACKAGE_REPO}"
  # set the package language folder
  VDM_PACKAGE_LANG_DIR="${VDM_PACKAGE_DIR}/languages"
  # set the package xml
  VDM_PACKAGE_XML="${VDM_PACKAGE_DIR}/${VDM_PACKAGE_NAME,,}.xml"
  # set the files xml
  VDM_FILES_XML="${VDM_MAIN_DIR}/files.xml"
  # set the languages xml
  VDM_LANGUAGES_XML="${VDM_MAIN_DIR}/languages.xml"
  # set the extensions list of files
  VDM_README_FILES_MD="${VDM_MAIN_DIR}/README_FILES.md"
  # set the extensions list of files (json, used for the manifest and outputs)
  VDM_FILES_JSON="${VDM_MAIN_DIR}/.${PROGRAM_CODE}_files.json"
  # set the README
  VDM_README_MD="${VDM_PACKAGE_DIR}/README.md"
  # set the license file
  VDM_LICENSE_FILE_PATH="${VDM_PACKAGE_DIR}/LICENSE"
  # set the package install script
  VDM_INSTALL_PHP="${VDM_PACKAGE_DIR}/install_${VDM_CODE_NAME,,}.php"
  # makes the project path available
  export VDM_PACKAGE_DIR
  export VDM_PACKAGE_GIT_DIR
  export VDM_PACKAGE_SRC_DIR
  export VDM_PACKAGE_LANG_DIR
  # makes the project file locations available
  export VDM_PACKAGE_XML
  export VDM_FILES_XML
  export VDM_LANGUAGES_XML
  export VDM_README_MD
  export VDM_INSTALL_PHP
  export VDM_LICENSE_FILE_PATH
  export VDM_FILES_JSON
  # make sure the packages dir is created
  mkdir -p "${VDM_PACKAGE_DIR}" || return 12
  #make sure the src dir is created
  mkdir -p "${VDM_PACKAGE_SRC_DIR}" || return 12
  #make sure the languages dir is created
  mkdir -p "${VDM_PACKAGE_LANG_DIR}" || return 12
  #make sure the git dir is created
  mkdir -p "${VDM_PACKAGE_GIT_DIR}" || return 12
  # success
  return 0
}

# set the Files
function setFiles() {
  # little information of progress
  _echo "[info] Loading the Files..."
  # make sure its reset
  echo -e '\t<files folder="src">' >"${VDM_FILES_XML}"
  echo "" >"${VDM_README_FILES_MD}"
  : >"${VDM_FILES_JSON}"
  # check for errors
  local has_error=false
  local has_files=false
  local required
  local file_count
  file_count=$(jq -er '.files | if type == "array" then length else error("files must be an array") end' <<<"${VDM_CONFIG_DATA}") || return 13
  # loop over the repos
  local i
  for ((i = 0; i < file_count; i++)); do
    # check for errors
    has_error=false
    # Missing extensions must never silently produce a partial package. An
    # intentionally optional extension can opt out explicitly in its config.
    required=$(echo "${VDM_CONFIG_DATA}" | jq -r ".files[$i].required != false")
    # get the global config values if not set
    setValueFromJson 'VDM_OWNER' ".files[$i].owner" "${VDM_CONFIG_DATA}" || has_error=true
    getConfigValue 'VDM_REPO' ".files[$i].repo" || has_error=true
    getConfigValue 'VDM_TYPE' ".files[$i].type" || has_error=true
    getConfigValue 'VDM_ID' ".files[$i].id" || has_error=true
    getConfigValue 'VDM_ENABLED' ".files[$i].enabled" false || VDM_ENABLED=1
    # check if we have some errors already
    if $has_error; then
      clearFileEnv
      $required && return 13
      continue
    fi
    # make sure the names are safe to use in paths
    if ! _valid_name "${VDM_OWNER}" || ! _valid_name "${VDM_REPO}"; then
      echo >&2 "[error] The file repository (${VDM_OWNER}/${VDM_REPO}) has an invalid owner or repository name, so it was skipped."
      clearFileEnv
      $required && return 13
      continue
    fi
    getConfigValue 'VDM_TOKEN_NAME' ".files[$i].token_name" false || VDM_TOKEN_NAME="VDM_GLOBAL_TOKEN"
    getConfigValue 'VDM_API_NAME' ".files[$i].api_name" false || VDM_API_NAME="VDM_GLOBAL_API"
    getConfigValue 'VDM_URL_NAME' ".files[$i].url_name" false || VDM_URL_NAME="VDM_GLOBAL_URL"
    getConfigValue 'VDM_MODE' ".files[$i].mode" false || VDM_MODE='tags'
    # set additional
    VDM_GROUP=''
    VDM_CLIENT=''
    VDM_TYPE_KEY=''
    VDM_TYPE_VAL=''
    if [ "$VDM_TYPE" = 'plugin' ]; then
      # set the plugin group
      getConfigValue 'VDM_GROUP' ".files[$i].group" || has_error=true
      # set the key
      VDM_TYPE_KEY="group"
      VDM_TYPE_VAL="${VDM_GROUP}"
    elif [ "$VDM_TYPE" = 'module' ] || [ "$VDM_TYPE" = 'template' ]; then
      # set module & template client
      getConfigValue 'VDM_CLIENT' ".files[$i].client" || has_error=true
      # set the key
      VDM_TYPE_KEY="client"
      VDM_TYPE_VAL="${VDM_CLIENT}"
    fi
    # check if we have some errors already
    if $has_error; then
      clearFileEnv
      $required && return 13
      continue
    fi
    # set the URL
    VDM_URL=${!VDM_URL_NAME}
    # set the API
    VDM_API=${!VDM_API_NAME}
    # set the token
    VDM_TOKEN=${!VDM_TOKEN_NAME}
    # export these values
    export VDM_OWNER
    export VDM_MODE
    export VDM_ENABLED
    export VDM_TYPE_KEY
    export VDM_TYPE_VAL
    export VDM_TOKEN
    export VDM_API
    export VDM_URL
    # get this zip packages
    if getZipFile; then
      # check if this is the package version ID
      if [ -n "${VDM_PACKAGE_VERSION_ID}" ] &&
        [ -z "${VDM_PACKAGE_VERSION}" ] &&
        [ "${VDM_PACKAGE_VERSION_ID}" = "${VDM_ID}" ]; then
        # set the package version
        VDM_PACKAGE_VERSION="${VDM_ZIP_VERSION:-$VDM_ZIP_NAME}"
        export VDM_PACKAGE_VERSION
      fi
      # we have a file
      has_files=true
    elif $required; then
      echo >&2 "[error] Required extension ${VDM_OWNER}/${VDM_REPO} could not be loaded. Aborting the package."
      clearFileEnv
      return 13
    fi
    # clear env
    clearFileEnv
  done
  # make sure to close the files
  echo -e '\t</files>' >>"${VDM_FILES_XML}"
  # check if we found a file
  $has_files || return 13
  # success
  return 0
}

# just to clear all file ENVs
function clearFileEnv() {
  # SET IN: setFiles
  unset VDM_OWNER
  unset VDM_REPO
  unset VDM_TYPE
  unset VDM_ID
  unset VDM_GROUP
  unset VDM_CLIENT
  unset VDM_TYPE_KEY
  unset VDM_TYPE_VAL
  unset VDM_TOKEN_NAME
  unset VDM_TOKEN
  unset VDM_API_NAME
  unset VDM_API
  unset VDM_URL_NAME
  unset VDM_URL
  unset VDM_MODE
  # SET IN: getFileByKey || getFileByRelease || getFileByTag
  unset VDM_ZIP_NAME
  unset VDM_ZIP_VERSION
  unset VDM_ZIP_MESSAGE
  unset VDM_RELEASE_ID
  unset VDM_ASSET_ID
  unset VDM_ASSET_DOWNLOAD
}

# get the repository zip package
function getZipFile() {
  local mode="tags"
  local target="Key"

  if [ "${VDM_MODE}" = 'tags' ] || [ "${VDM_MODE}" = 'releases' ]; then
    mode="${VDM_MODE}"
    target="${VDM_MODE^}"
  elif [[ "${VDM_MODE}" == branch:* ]]; then
    VDM_MODE="${VDM_MODE#branch:}"
  fi

  # An explicit ref can be fetched directly, including the first tag or an
  # untagged branch. Listing tags first would reject otherwise valid refs.
  if [ "${target}" = 'Key' ]; then
    getFileByKey
    return $?
  fi

  callGiteaAPI "${mode}" "${VDM_OWNER}" "${VDM_REPO}" "${VDM_API}" "${VDM_TOKEN}" || return 11

  if [ -n "${VDM_API_BUCKET}" ]; then
    "getFileBy${target}" || return 11
  else
    return 11
  fi

  return 0
}

# get the file by tag
function getFileByTags() {
  local zip_name
  # get the name
  setValueFromJson "VDM_ZIP_NAME" ".[0].name" "${VDM_API_BUCKET}" || {
    _echo "[error] Tag name not found in VDM_API_BUCKET."
    return 12
  }
  # get the message
  # GitHub's tags API has no message field (Gitea does).
  setValueFromJson "VDM_ZIP_MESSAGE" ".[0].message" "${VDM_API_BUCKET}" || VDM_ZIP_MESSAGE="Release ${VDM_ZIP_NAME}"
  zip_name="${VDM_OWNER}__${VDM_REPO}__$(jq -rn --arg ref "${VDM_ZIP_NAME}" '$ref | @uri').zip"
  # download the zip file if not already set
  if [ ! -f "${VDM_PACKAGE_SRC_DIR}/${zip_name}" ]; then
    # give message
    _echo "[info] Downloading the (${VDM_OWNER}-${VDM_REPO}-${VDM_ZIP_NAME}.zip) package."
    local archive_url
    archive_url=$(getValueFromJson '.[0].zipball_url' "${VDM_API_BUCKET}") || archive_url=$(getArchiveUrl "${VDM_ZIP_NAME}")
    downloadExtensionZip "${archive_url}" "${VDM_PACKAGE_SRC_DIR}/${zip_name}" || return 12
  else
    # zip already set
    _echo "[error] ${zip_name} already set."
    return 12
  fi
  # add file to xml
  setFileToXML "${zip_name}"
  # update the readme
  setFileToREADME
  # success
  return 0
}

# get the file by tag
function getFileByReleases() {
  # check that we got some file
  local has_files=false
  local i=0
  # get the name
  setValueFromJson "VDM_ZIP_NAME" ".[0].tag_name" "${VDM_API_BUCKET}" || {
    _echo "[error] Release name not found in VDM_API_BUCKET."
    return 12
  }
  # get the message
  setValueFromJson "VDM_ZIP_MESSAGE" ".[0].name" "${VDM_API_BUCKET}" || {
    _echo "[error] Release message not found in VDM_API_BUCKET."
    return 12
  }
  # we may have multiple assets (but we only load the first ZIP file we get)
  # because we can only have the ${VDM_ID} only once in the xml file
  for asset_zip_file_name in $(echo "${VDM_API_BUCKET}" | jq -r '.[0].assets[]?.name'); do
    # make sure we did not already get a file
    $has_files && {
      # increment
      ((i++))
      continue
    }
    # we only work with zip files for now
    [[ "$asset_zip_file_name" == *".zip" ]] || {
      # increment
      ((i++))
      continue
    }
    # download the zip file if not already set
    if [ ! -f "${VDM_PACKAGE_SRC_DIR}/${VDM_OWNER}__${asset_zip_file_name}" ]; then
      # get download link
      setValueFromJson "VDM_ASSET_DOWNLOAD" ".[0].assets[$i].browser_download_url" "${VDM_API_BUCKET}" || {
        _echo "[error] Asset [$i].browser_download_url for (${asset_zip_file_name}) not found in VDM_API_BUCKET."
        # increment
        ((i++))
        continue
      }
      # give message
      _echo "[info] Downloading the (${VDM_OWNER}-${asset_zip_file_name}) package."
      downloadExtensionZip "${VDM_ASSET_DOWNLOAD}" "${VDM_PACKAGE_SRC_DIR}/${VDM_OWNER}__${asset_zip_file_name}" || return 12
      # so we got a file
      has_files=true
      # add to xml file
      setFileToXML "${VDM_OWNER}__${asset_zip_file_name}"
      # update the readme
      setFileToREADME "${VDM_ZIP_NAME}" "${VDM_ASSET_DOWNLOAD}"
    else
      # zip already set
      _echo "[notice] ${VDM_OWNER}__${asset_zip_file_name} already set."
    fi
    # increment
    ((i++))
  done
  # check if we got a file
  $has_files || return 12
  # success
  return 0
}

# get the file by key
function getFileByKey() {
  # set some local values
  local folder_path
  local zip_name
  local ref_name
  # get the name
  VDM_ZIP_NAME="${VDM_MODE}"
  # get the message
  VDM_ZIP_MESSAGE="${VDM_MODE}"
  # set the zip name
  ref_name=$(jq -rn --arg ref "${VDM_ZIP_NAME}" '$ref | @uri') || return 12
  zip_name="${VDM_OWNER}__${VDM_REPO}__${ref_name}.zip"
  # set the folder path
  folder_path="${VDM_OWNER}_${VDM_REPO}_${ref_name}"
  # download the zip file if not already set
  if [ ! -f "${VDM_PACKAGE_SRC_DIR}/${zip_name}" ]; then
    # give message
    _echo "[info] Downloading the (${VDM_OWNER}-${VDM_REPO}-${VDM_ZIP_NAME}.zip) package."
    # download the zip file
    downloadExtensionZip "$(getArchiveUrl "${VDM_ZIP_NAME}")" "${VDM_PACKAGE_SRC_DIR}/${zip_name}" || return 12
  else
    # zip already set
    _echo "[error] ${zip_name} already set."
    return 12
  fi
  # unzip this zip file
  _unzip "${zip_name}" "${folder_path}" || {
    _echo "[error] We encountered and error, we could not unzip (${VDM_PACKAGE_SRC_DIR}/${zip_name}) in to (${VDM_PACKAGE_GIT_DIR}/${folder_path})"
    # so we skip this package
    return 12
  }
  # check if we have a folder to access
  if ! cd "${VDM_PACKAGE_GIT_DIR}/${folder_path}"; then
    _echo "[error] We could not open the package folder."
    exit 13
  fi
  # get the version from the current directory
  _xml_version || {
    _echo "[error] Version name not found in package. (but ignored since we are getting file by key)"
    VDM_ZIP_VERSION="${VDM_MODE}"
    export VDM_ZIP_VERSION
  }
  # move out of the directory
  cd "${VDM_MAIN_DIR}" || exit 13
  # always remove the package folder again
  rm -fr "${VDM_PACKAGE_GIT_DIR:?}/${folder_path:?}"
  # move the tag values to global scope
  export VDM_ZIP_NAME
  export VDM_ZIP_MESSAGE
  # add file to xml
  setFileToXML "${zip_name}"
  # update the readme
  setFileToREADME
  # success
  return 0
}

# GitHub and Gitea use different archive endpoints. The public Git host also
# identifies GitHub when its API is proxied; /api/v3 identifies GitHub Enterprise.
function getArchiveUrl() {
  local ref
  ref=$(jq -rn --arg ref "${1}" '$ref | @uri') || return 12
  case "${VDM_URL}:${VDM_API%/}" in
  github.com:* | *:https://api.github.com | *:*/api/v3)
    printf '%s/repos/%s/%s/zipball/%s' "${VDM_API%/}" "${VDM_OWNER}" "${VDM_REPO}" "${ref}"
    ;;
  *)
    printf '%s/repos/%s/%s/archive/%s.zip' "${VDM_API%/}" "${VDM_OWNER}" "${VDM_REPO}" "${ref}"
    ;;
  esac
}

# Never include an HTTP error page or a truncated download as an extension.
function downloadExtensionZip() {
  local url="${1}"
  local destination="${2}"
  local temporary="${destination}.part"
  if ! curl --fail --silent --show-error --location --retry 3 \
    -H "Authorization: token ${VDM_TOKEN}" "${url}" -o "${temporary}" ||
    ! unzip -tq "${temporary}" >/dev/null 2>&1; then
    rm -f -- "${temporary}"
    _echo "[error] Could not download a valid ZIP for ${VDM_OWNER}/${VDM_REPO} (${VDM_ZIP_NAME})."
    return 12
  fi
  mv -- "${temporary}" "${destination}"
}

# set the File Details to XML
function setFileToREADME() {
  local tmp_zip_name="${VDM_ZIP_NAME}"
  local zip_name="${1:-$tmp_zip_name}"
  local tmp_zip_url="https://${VDM_URL}/${VDM_OWNER}/${VDM_REPO}/archive/${VDM_ZIP_NAME}.zip"
  local zip_url="${2:-$tmp_zip_url}"
  local tmp_message="${VDM_ZIP_MESSAGE}"
  local message="${3:-$tmp_message}"
  # set the readme list of extensions
  {
    echo -n "- [${VDM_OWNER}/${VDM_REPO}]"
    echo -n "(https://${VDM_URL}/${VDM_OWNER}/${VDM_REPO})"
    echo " [${zip_name}](${zip_url})"
    echo "> ${message}"
  } >>"${VDM_README_FILES_MD}"
}

# set the File Details to XML
function setFileToXML() {
  local tmp_zip_name="${VDM_OWNER}__${VDM_REPO}__${VDM_ZIP_NAME}.zip"
  local zip_name="${1:-$tmp_zip_name}"
  # add the file xml details
  {
    echo -en '\t\t<file type="'
    echo -n "${VDM_TYPE}"
    echo -n '" id="'
    echo -n "${VDM_ID}"
    echo -n '"'
    [[ -n "${VDM_TYPE_KEY}" ]] &&
      echo -n " ${VDM_TYPE_KEY}=" &&
      echo -n '"' &&
      echo -n "${VDM_TYPE_VAL}" &&
      echo -n '"'
    echo ">$zip_name</file>"
  } >>"${VDM_FILES_XML}"
  # add the file details to the json list (used for the manifest and outputs)
  setFileToJson "${zip_name}"
}

# set the File Details to JSON
function setFileToJson() {
  local zip_name="${1}"
  local mode="${VDM_MODE}"
  # anything that is not tags or releases is a branch
  [ "${mode}" = 'tags' ] || [ "${mode}" = 'releases' ] || mode='branch'
  # add the file json details (one object per line)
  jq -cn \
    --arg owner "${VDM_OWNER}" \
    --arg repo "${VDM_REPO}" \
    --arg url "https://${VDM_URL}/${VDM_OWNER}/${VDM_REPO}" \
    --arg type "${VDM_TYPE}" \
    --arg id "${VDM_ID}" \
    --arg key "${VDM_TYPE_KEY}" \
    --arg val "${VDM_TYPE_VAL}" \
    --arg mode "${mode}" \
    --arg ref "${VDM_ZIP_NAME}" \
    --arg version "${VDM_ZIP_VERSION:-$VDM_ZIP_NAME}" \
    --arg message "${VDM_ZIP_MESSAGE}" \
    --arg file "src/${zip_name}" \
    '{owner: $owner, repo: $repo, url: $url, type: $type, id: $id, mode: $mode, ref: $ref, version: $version, message: $message, file: $file}
      + (if $key != "" then {($key): $val} else {} end)' >>"${VDM_FILES_JSON}"
}

# make API call
function callGiteaAPI() {
  # the locals
  local mode="${1}"
  local owner="${2}"
  local repo="${3}"
  local api="${4}"
  local token="${5}"
  local json_data
  local message
  local url
  # each time reset
  unset VDM_API_BUCKET
  # give message
  _echo "[info] Getting ${mode} information from ${owner}/${repo} repository."
  # get the json data
  # Check if mode is "tags"
  if [ "${mode}" = "tags" ]; then
    url="${api}/repos/${owner}/${repo}/${mode}?page=1"
  else
    url="${api}/repos/${owner}/${repo}/${mode}"
  fi
  # get the json data
  json_data=$(curl -s -H "Authorization: token ${token}" -H 'accept: application/json' -X 'GET' "${url}")
  # check for error
  if [[ "${json_data}" =~ '"errors"' ]] && [[ "${json_data}" =~ '"message"' ]]; then
    # get the message
    message=$(echo "${json_data}" | jq -r ".message")
    # check that we have tags (not ideal, but to catch wrong repo path)
    _echo "[error] failed to get ${mode} from ${owner}/${repo} repository [${message}]."
    # we an add more later
    return 12
  elif [ "${json_data}" = '[]' ]; then
    # check that we have tags (not ideal, but to catch wrong repo path)
    _echo "[error] failed to get ${mode} from ${owner}/${repo} repository."
    # we an add more later
    return 12
  fi
  # get the latest
  VDM_API_BUCKET="${json_data}"
  # success
  export VDM_API_BUCKET
  # success
  return 0
}

# set the package language file and xml
function setLanguages() {
  # little information of progress
  _echo "[info] Loading the Languages..."
  # make sure its reset
  echo -e '\t<languages folder="languages">' >"${VDM_LANGUAGES_XML}"
  # check for errors
  local has_error
  # loop over the repos
  i=0
  for vdm_lang_tag in $(echo "${VDM_CONFIG_DATA}" | jq -r '.languages[]?.tag'); do
    # check for errors
    has_error=false
    # get the config values needed
    getConfigValue 'vdm_lang_ini' ".languages[$i].ini" || has_error=true
    getConfigValue 'vdm_lang_key' ".languages[$i].key" || has_error=true
    getConfigValue 'vdm_lang_value' ".languages[$i].value" || has_error=true
    # check if we have some errors already
    if $has_error; then
      clearLangEnv
      continue
    fi
    # set file name
    # shellcheck disable=SC2154
    language_file_name="${vdm_lang_tag}.${VDM_PACKAGE_NAME,,}.${vdm_lang_ini}"
    # set file path
    language_file_path="${VDM_PACKAGE_LANG_DIR}/${vdm_lang_tag}/${language_file_name}"
    # build the language string
    # shellcheck disable=SC2154
    language_string="${vdm_lang_key}="
    language_string+='"'
    # shellcheck disable=SC2154
    language_string+="${vdm_lang_value}"
    language_string+='"'
    # create dir for language and add to xml only once
    if [ ! -d "${VDM_PACKAGE_LANG_DIR}/${vdm_lang_tag}" ]; then
      # create the language directory
      mkdir -p "${VDM_PACKAGE_LANG_DIR}/${vdm_lang_tag}"
    fi
    # add value to language file
    if [ -f "${language_file_path}" ]; then
      echo "${language_string}" >>"${language_file_path}"
    else
      # first time
      echo "${language_string}" >"${language_file_path}"
      # add to xml
      setLanguageXml "${vdm_lang_tag}" "${vdm_lang_tag}/${language_file_name}"
    fi
    # increment
    ((i++))
    # keep the packager language strings (used to resolve the package name and description)
    [ "${vdm_lang_tag}" = "${VDM_PACKAGER_LANG}" ] && VDM_LANG_STRINGS["${vdm_lang_key}"]="${vdm_lang_value}"
    # remove values
    clearLangEnv
  done
  # make sure its reset
  echo -e '\t</languages>' >>"${VDM_LANGUAGES_XML}"
}

# just to clear all file ENVs
function clearLangEnv() {
  # SET IN: setLanguages
  unset vdm_lang_tag
  unset vdm_lang_ini
  unset vdm_lang_key
  unset vdm_lang_value
}

# set the Language XML Details
function setLanguageXml() {
  # add the file details
  {
    echo -en '\t\t<language tag="'
    echo -n "${1}"
    echo -n '">'
    echo -n "${2}"
    echo '</language>'
  } >>"${VDM_LANGUAGES_XML}"
}

# set the Package XML Details
function setPackageXml() {
  # little information of progress
  _echo "[info] Setting the Package XML..."
  # set the local version
  local version
  # remove the v in front of the version (number-state-number)
  version="${VDM_PACKAGE_VERSION:-1.0.0}"
  version="${version/#v/}"
  # add the package details
  {
    echo '<?xml version="1.0" encoding="utf-8"?>'
    echo -n '<extension version="'
    echo -n "${VDM_MIN_JOOMLA_VERSION:-3.8}"
    echo '" type="package" method="upgrade">'
    # set the name
    echo -en '\t<name>'
    echo -n "${VDM_NAME}"
    echo '</name>'
    # set the package name
    echo -en '\t<packagename>'
    echo -n "${VDM_CODE_NAME,,}"
    echo '</packagename>'
    # set the version
    echo -en '\t<version>'
    echo -n "${version}"
    echo '</version>'
    # set the creationDate
    echo -en '\t<creationDate>'
    echo -n "${CREATION_DATE}"
    echo '</creationDate>'
    # set the author
    echo -en '\t<author>'
    echo -n "${VDM_AUTHOR}"
    echo '</author>'
    # set the authorEmail
    echo -en '\t<authorEmail>'
    echo -n "${VDM_AUTHOR_EMAIL}"
    echo '</authorEmail>'
    # set the authorUrl
    echo -en '\t<authorUrl>'
    echo -n "${VDM_AUTHOR_URL}"
    echo '</authorUrl>'
    # set the copyright
    echo -en '\t<copyright>'
    echo -n "${VDM_COPYRIGHT}"
    echo '</copyright>'
    # set the copyrightyear
    echo -en '\t<copyrightyear>'
    echo -n "${VDM_COPYRIGHT_YEAR:-$CREATION_YEAR}"
    echo '</copyrightyear>'
    # set the license
    echo -en '\t<license>'
    echo -n "${VDM_LICENSE}"
    echo '</license>'
    # set the packager
    echo -en '\t<packager>'
    echo -n "${VDM_PACKAGER:-$PROGRAM_NAME}"
    echo '</packager>'
    # set the packagerurl
    echo -en '\t<packagerurl>'
    echo -n "${VDM_PACKAGER_URL:-$PROGRAM_URL}"
    echo '</packagerurl>'
    # set the description
    echo -en '\t<description>'
    echo -n "${VDM_DESCRIPTION}"
    echo '</description>'
    # set the script file if found
    if [ -n "${VDM_INSTALLATION_FILE}" ]; then
      echo -en '\t<scriptfile>'
      echo -n "install_${VDM_CODE_NAME,,}.php"
      echo '</scriptfile>'
    fi
    # set the update server if found
    if [ -n "${VDM_UPDATE_SERVER}" ]; then
      echo -e '\t<updateservers>'
      echo -en '\t\t<server type="extension" name="'
      echo -n "$(_human_name "${VDM_NAME}")"
      echo -n ' - Updates" element="'
      echo -n "${VDM_PACKAGE_NAME}"
      echo -n '">'
      printf '%s' "$(jq -rn --arg url "${VDM_UPDATE_SERVER}" '$url | @html')"
      echo '</server>'
      echo -e '\t</updateservers>'
    fi
    # set the changelog server url if found
    if [ -n "${VDM_CHANGELOG_SERVER}" ]; then
      printf '\t<changelogurl>%s</changelogurl>\n' "$(jq -rn --arg url "${VDM_CHANGELOG_SERVER}" '$url | @html')"
    fi
    # add the languages
    cat "${VDM_LANGUAGES_XML}"
    # add the files
    cat "${VDM_FILES_XML}"
    # close the extension xml
    echo '</extension>'
  } >"${VDM_PACKAGE_XML}"
  # remove file no longer needed
  rm "${VDM_LANGUAGES_XML}"
  rm "${VDM_FILES_XML}"
}

# set the package README
function setReadMe() {
  # little information of progress
  _echo "[info] Setting the README..."
  # add the Project Name to Readme
  {
    echo -n "# $(_human_name "${VDM_NAME}")"
    # add the version
    echo " (${VDM_PACKAGE_VERSION:-1.0.0})"
    echo ""
    # set the Description (resolves a language constant when loaded)
    _human_name "${VDM_DESCRIPTION}"
    echo ""
    echo "## Details"
    echo ""
    echo "- Packager: [${VDM_PACKAGER}](${VDM_PACKAGER_URL})"
    echo "- Author: [${VDM_AUTHOR}](${VDM_AUTHOR_URL})"
    echo "- Creation Date: ${CREATION_DATE}"
    [ -n "${VDM_MAX_JOOMLA_VERSION}" ] && echo "- Max Joomla Version: J${VDM_MAX_JOOMLA_VERSION}"
    echo "- Minimum Joomla Version: J${VDM_MIN_JOOMLA_VERSION}"
    echo ""
    echo "## Extensions"
    # add the list of extensions
    cat "${VDM_README_FILES_MD}"
    echo ""
    echo "### Copyright (${VDM_COPYRIGHT_YEAR:-$CREATION_YEAR})"
    echo "> ${VDM_COPYRIGHT}"
    echo "### License"
    echo "> ${VDM_LICENSE}"
    echo ""
  } >"${VDM_README_MD}"
  # remove the Readme files build
  rm "${VDM_README_FILES_MD:?}"
}

# set the license file
function setLicenseFile() {
  local has_error=false
  # check if the license file is passed via a URL
  if [[ "${VDM_LICENSE_FILE}" =~ ^"http:" ]] || [[ "${VDM_LICENSE_FILE}" =~ ^"https:" ]]; then
    # shellcheck disable=SC2143
    if [[ $(wget -S --spider "${VDM_LICENSE_FILE}" 2>&1 | grep 'HTTP/1.1 200 OK') ]]; then
      wget --quiet "${VDM_LICENSE_FILE}" -O "${VDM_LICENSE_FILE_PATH}"
      VDM_LICENSE_FILE="LICENSE"
    else
      echo >&2 "[error] The license:${VDM_LICENSE_FILE} is not a valid URL."
      has_error=true
    fi
  elif [ -f "${VDM_LICENSE_DIR}/${VDM_LICENSE_FILE}" ]; then
    # now copy the license file
    cp "${VDM_LICENSE_DIR}/${VDM_LICENSE_FILE}" "${VDM_LICENSE_FILE_PATH}"
  else
    echo >&2 "[error] The license:${VDM_LICENSE_DIR}/${VDM_LICENSE_FILE} not found."
    has_error=true
  fi
  # check if we have some errors
  if $has_error; then
    return 16
  fi
  # little information of progress
  _echo "[info] Setting the License File..."
  return 0
}

# set the install file
function setInstallFile() {
  local has_error=false
  # a relative file path is relative to the directory the program was started in
  if [ -n "${VDM_INSTALLATION_FILE}" ] && ! [[ "${VDM_INSTALLATION_FILE}" =~ ^https?: ]]; then
    VDM_INSTALLATION_FILE="$(_abs_path "${VDM_INSTALLATION_FILE}")"
  fi
  # check if the installation script file is passed via a URL
  if [[ "${VDM_INSTALLATION_FILE}" =~ ^"http:" ]] || [[ "${VDM_INSTALLATION_FILE}" =~ ^"https:" ]]; then
    # shellcheck disable=SC2143
    if [[ $(wget -S --spider "${VDM_INSTALLATION_FILE}" 2>&1 | grep 'HTTP/1.1 200 OK') ]]; then
      wget --quiet "${VDM_INSTALLATION_FILE}" -O "${VDM_INSTALL_PHP}"
    else
      echo >&2 "[error] The installation script file:${VDM_INSTALLATION_FILE} is not a valid URL."
      has_error=true
    fi
  elif [ -f "${VDM_INSTALLATION_FILE}" ]; then
    # now copy the installation script file
    cp "${VDM_INSTALLATION_FILE}" "${VDM_INSTALL_PHP}"
  fi
  # check if we have some errors
  if $has_error; then
    return 16
  fi
  # little information of progress
  _echo "[info] Setting the Installation.php File..."
  return 0
}

# get the package repository
function setRepository() {
  # make sure the SSH key (when set) is also used for the ls-remote and clone calls
  if [ -n "${GIT_SSH_KEY_PATH}" ] && [ -z "${GIT_SSH_COMMAND}" ]; then
    export GIT_SSH_COMMAND="ssh -i '${GIT_SSH_KEY_PATH}'"
  fi
  # nothing pushed yet
  VDM_REPOSITORY_STATUS='unchanged'
  export VDM_REPOSITORY_STATUS
  # change to git directory
  cd "${VDM_PACKAGE_GIT_DIR}" || return 22
  # check if the repository exist on our gitea instance
  local update_repo
  # shellcheck disable=SC2015
  if git ls-remote --exit-code --heads "git@${VDM_PACKAGE_URL}:${VDM_PACKAGE_OWNER}/${VDM_PACKAGE_REPO}.git" >/dev/null 2>&1; then
    getExistingRepository || return 23
    update_repo=true
  else
    setNewRepository || return 24
    update_repo=false
  fi
  # make sure we are in the correct dir and then remove all existing data
  cd "${VDM_PACKAGE_GIT_DIR}/${VDM_PACKAGE_REPO}" || return 25
  # remove any existing files and folders from repository
  rm -rf -- * || return 26
  # move all new files into repository
  setRepositoryNewFiles || return 27
  # check if we have changes
  if [[ "${update_repo}" == true && -z $(git status --porcelain) ]]; then
    _echo "[info] No changes found in (${VDM_PACKAGE_OWNER}/${VDM_PACKAGE_REPO}) repository"
    # Recover a previous branch-only publication without manufacturing a commit
    # or moving an existing release tag.
    if ! git show-ref --verify --quiet "refs/tags/${VDM_PACKAGE_VERSION:-1.0.0}"; then
      setUserDetails
      git tag -m "Release ${VDM_PACKAGE_VERSION:-1.0.0}" "${VDM_PACKAGE_VERSION:-1.0.0}" || return 28
      pushRepositoryRefs || return 30
      VDM_REPOSITORY_STATUS='pushed'
    fi
  else
    # check if we must update or create repository
    if [[ "${update_repo}" == true ]]; then
      # Check the cloned Git refs, without a paginated hosting API lookup.
      VDM_TAG_EXIST=false
      git show-ref --verify --quiet "refs/tags/${VDM_PACKAGE_VERSION:-1.0.0}" && VDM_TAG_EXIST=true
      # set update message
      if $VDM_TAG_EXIST; then
        message="Update - ${VDM_PACKAGE_VERSION:-1.0.0}"
      else
        message="Update"
      fi
      # add user details
      setUserDetails
      # get the repository last tag
      makeGitCommit "${message}" "${VDM_PACKAGE_VERSION:-1.0.0}" "$VDM_TAG_EXIST" || return 28
      # give little notice of progress
      _echo "[info] Pushing changes to (${VDM_PACKAGE_OWNER}/${VDM_PACKAGE_REPO}) repository"
      pushRepositoryRefs || return 30
      # we pushed
      VDM_REPOSITORY_STATUS='pushed'
    else
      # create new repo
      setGitRepository || return 29
      # give little notice of progress
      _echo "[info] Pushing (TO CREATE) changes to (${VDM_PACKAGE_OWNER}/${VDM_PACKAGE_REPO}) repository"
      pushRepositoryRefs || return 30
      # we pushed
      VDM_REPOSITORY_STATUS='pushed'
    fi
  fi
  # success
  return 0
}

# Publish only this branch and release tag, together. If either ref is rejected,
# neither becomes visible; an existing tag is never overwritten.
function pushRepositoryRefs() {
  local branch
  branch=$(git symbolic-ref --short HEAD) || return 30
  git push --atomic --set-upstream origin "HEAD:refs/heads/${branch}" \
    "refs/tags/${VDM_PACKAGE_VERSION:-1.0.0}" >/dev/null 2>&1
}

# get the existing repository
function getExistingRepository() {
  # little information of progress
  _echo "[info] Getting (${VDM_PACKAGE_OWNER}/${VDM_PACKAGE_REPO}) repository"
  if [[ "${VDM_PACKAGE_REPO_BRANCH}" == 'default' ]]; then
    # clone the existing repository
    git clone "git@${VDM_PACKAGE_URL}:${VDM_PACKAGE_OWNER}/${VDM_PACKAGE_REPO}.git" >/dev/null 2>&1 || return 23
  else
    # clone the existing repository
    git clone -b "${VDM_PACKAGE_REPO_BRANCH:-master}" "git@${VDM_PACKAGE_URL}:${VDM_PACKAGE_OWNER}/${VDM_PACKAGE_REPO}.git" >/dev/null 2>&1 || return 23
  fi
  # success
  return 0
}

# set the new repository
function setNewRepository() {
  # little information of progress
  _echo "[info] Creating (${VDM_PACKAGE_OWNER}/${VDM_PACKAGE_REPO}) folder"
  # check if the repository exist on our gitea instance
  mkdir -p "${VDM_PACKAGE_GIT_DIR}/${VDM_PACKAGE_REPO}" || return 24
  # success
  return 0
}

# set new git repository
function setGitRepository() {
  # little information of progress
  _echo "[info] Initializing the (${VDM_PACKAGE_OWNER}/${VDM_PACKAGE_REPO}) repository"
  # initialize the repository
  git init >/dev/null 2>&1 || return 29
  # add user details
  setUserDetails
  # add the first commit
  makeGitCommit "First Commit - ${VDM_PACKAGE_VERSION:-1.0.0}" "${VDM_PACKAGE_VERSION:-1.0.0}" >/dev/null 2>&1 || return 28
  # little information of progress
  _echo "[info] Adding remote branch to (${VDM_PACKAGE_OWNER}/${VDM_PACKAGE_REPO}) repository"
  # add the remote branch
  git remote add origin "git@${VDM_PACKAGE_URL}:${VDM_PACKAGE_OWNER}/${VDM_PACKAGE_REPO}.git" >/dev/null 2>&1 || return 29
  # Check if a specific branch is set and it is not 'default'
  if [ "${VDM_PACKAGE_REPO_BRANCH}" != "default" ]; then
    _echo "[info] Setting branch to ${VDM_PACKAGE_REPO_BRANCH}"
    git checkout -b "${VDM_PACKAGE_REPO_BRANCH}" >/dev/null 2>&1 || return 29
  fi
  #success
  return 0
}

# Set Git user details based on environment variables
function setUserDetails () {
  # Set Git author name
  if [ -n "${GIT_AUTHOR_NAME+x}" ]; then
    git config user.name "${GIT_AUTHOR_NAME}"
    _echo "[info] Git author name set to: ${GIT_AUTHOR_NAME}"
  fi

  # Set Git author email
  if [ -n "${GIT_AUTHOR_EMAIL+x}" ]; then
    git config user.email "${GIT_AUTHOR_EMAIL}"
    _echo "[info] Git author email set to: ${GIT_AUTHOR_EMAIL}"
  fi

  # Set signing key
  if [ -n "${GIT_SIGNING_KEY+x}" ]; then
    git config user.signingKey "${GIT_SIGNING_KEY}"
    _echo "[info] Git signing key set to: ${GIT_SIGNING_KEY}"
  fi

  # Set Git GPG sign
  if [ -n "${GIT_GPG_SIGN+x}" ]; then
    git config commit.gpgsign "${GIT_GPG_SIGN}"
    _echo "[info] Git GPG sign set to: ${GIT_GPG_SIGN}"
  fi

  # Set Git SSH key path
  if [ -n "${GIT_SSH_KEY_PATH+x}" ]; then
    git config core.sshCommand "ssh -i '${GIT_SSH_KEY_PATH}'"
    _echo "[info] Git SSH key path set to: ${GIT_SSH_KEY_PATH}"
  fi
}

# make the git commit
function makeGitCommit() {
  # add all (or remove)
  git add . >/dev/null 2>&1 || return 28
  # little information of progress
  _echo "[info] Committing (${1}) to (${VDM_PACKAGE_OWNER}/${VDM_PACKAGE_REPO}) repository"
  # set the commit message
  git commit -am"${1}" >/dev/null 2>&1 || return 28
  # check if the tag should be added
  if "${3:-false}"; then
    # little information of progress
    _echo "[info] TAG (${2}) in (${VDM_PACKAGE_OWNER}/${VDM_PACKAGE_REPO}) already exists"
  else
    # little information of progress
    _echo "[info] Adding TAG (${2}) to (${VDM_PACKAGE_OWNER}/${VDM_PACKAGE_REPO}) repository"
    # add the new tag
    git tag -m "Release ${2}" "${2}" >/dev/null 2>&1 || return 28
  fi
  # success
  return 0
}

# add all the new files to the repository
function setRepositoryNewFiles() {
  # make sure we have the package directory
  [ -d "${VDM_PACKAGE_DIR}" ] || return 27
  # copy the files when we must keep them, else move them
  if _is_true "${VDM_KEEP_FILES}"; then
    # little information of progress
    _echo "[info] Copying new files into the (${VDM_PACKAGE_OWNER}/${VDM_PACKAGE_REPO}) directory"
    cp -a "${VDM_PACKAGE_DIR:?}/." "${VDM_PACKAGE_GIT_DIR}/${VDM_PACKAGE_REPO}" >/dev/null 2>&1 || return 27
  else
    # little information of progress
    _echo "[info] Moving new files into the (${VDM_PACKAGE_OWNER}/${VDM_PACKAGE_REPO}) directory"
    _echo "[info] Removing the ${VDM_PACKAGE_DIR:?} directory"
    mv "${VDM_PACKAGE_DIR:?}/"* "${VDM_PACKAGE_GIT_DIR}/${VDM_PACKAGE_REPO}" >/dev/null 2>&1 &&
      rm -rf "${VDM_PACKAGE_DIR:?}" >/dev/null 2>&1 ||
      return 27
  fi
  # success
  return 0
}

# gives us a unique file name for any url
function getUniqueFileName() {
  local url="$1"
  local hash
  hash=$(echo "$url" | sha256sum | awk '{print $1}')
  echo "${hash:0:10}"
}

# Get the version from the current directory
function _xml_version() {
  local version=""
  local shortest_depth=100
  local file
  local v
  local depth

  # Find XML files excluding config.xml, access.xml, default.xml
  while IFS= read -r file; do
    # Ensure file does not match exclusions
    case "$file" in
      *config.xml|*access.xml|*default.xml) continue ;;
    esac

    # Ensure it's an extension XML (check if it has a <extension> root tag anywhere)
    if ! grep -iq '^[[:space:]]*<extension[[:space:]>]' "$file"; then
      continue
    fi

    # Extract version if present in XML
    v=$(sed -n 's|.*<version>\(.*\)</version>.*|\1|p' "$file" | head -n1)

    # Skip if no version found
    [[ -z "$v" ]] && continue

    # Determine folder depth (count slashes)
    depth=$(tr -cd '/' <<< "$file" | wc -c)

    # Choose the file with the shortest path (highest in folder stack)
    if (( depth < shortest_depth )); then
      shortest_depth=$depth
      version=$v

      # Since we want the highest-up file, and this is the shallowest so far,
      # we can break early if it's at root level (depth 1)
      (( depth <= 1 )) && break
    fi

  done < <(find . -type f -iname '*.xml')

  # Return failure if no version is found
  if [[ -z "$version" ]]; then
    return 14
  fi

  # Ensure version starts with 'v'
  [[ $version != v* ]] && version="v${version}"

  # Export version
  export VDM_ZIP_VERSION="$version"

  return 0
}

# build the package zip file (Joomla installable package)
function setPackageZip() {
  # we need the zip command for this
  command -v zip >/dev/null 2>&1 || {
    echo >&2 "[error] We require zip to build the package zip file for $PROGRAM_NAME v${PROGRAM_V}, but it's not installed."
    return 31
  }
  # little information of progress
  _echo "[info] Building the Package Zip..."
  # set the zip directory (default: <main-dir>/packages)
  VDM_PACKAGE_ZIP_DIR="${VDM_PACKAGE_ZIP_DIR:-${VDM_MAIN_DIR}/packages}"
  # set the zip name (default: <package_name>_<tag>.zip)
  VDM_PACKAGE_ZIP_NAME="${VDM_PACKAGE_ZIP_NAME:-${VDM_PACKAGE_NAME,,}_${VDM_PACKAGE_VERSION:-1.0.0}.zip}"
  # make sure the name is safe to use as a file name
  VDM_PACKAGE_ZIP_NAME="$(_safe_name "${VDM_PACKAGE_ZIP_NAME}")" || return 31
  # make sure we have the zip extension
  [[ "${VDM_PACKAGE_ZIP_NAME}" == *.zip ]] || VDM_PACKAGE_ZIP_NAME="${VDM_PACKAGE_ZIP_NAME}.zip"
  # set the zip path
  VDM_PACKAGE_ZIP_PATH="${VDM_PACKAGE_ZIP_DIR}/${VDM_PACKAGE_ZIP_NAME}"
  # make sure the zip directory exists
  mkdir -p "${VDM_PACKAGE_ZIP_DIR}" || return 31
  # always remove the previous zip file (if found)
  rm -f "${VDM_PACKAGE_ZIP_PATH:?}"
  # build the zip from inside the package directory (so the paths are relative)
  (cd "${VDM_PACKAGE_DIR}" && zip -qr -X "${VDM_PACKAGE_ZIP_PATH}" .) || return 31
  # get the checksum
  VDM_PACKAGE_ZIP_SHA256=$(sha256sum "${VDM_PACKAGE_ZIP_PATH}" | awk '{print $1}') || return 31
  # write the checksum file (in the format sha256sum -c expects)
  VDM_PACKAGE_ZIP_SHA256_FILE="${VDM_PACKAGE_ZIP_PATH%.zip}.sha256"
  echo "${VDM_PACKAGE_ZIP_SHA256}  ${VDM_PACKAGE_ZIP_NAME}" >"${VDM_PACKAGE_ZIP_SHA256_FILE}" || return 31
  # make globally available
  export VDM_PACKAGE_ZIP_DIR
  export VDM_PACKAGE_ZIP_NAME
  export VDM_PACKAGE_ZIP_PATH
  export VDM_PACKAGE_ZIP_SHA256
  export VDM_PACKAGE_ZIP_SHA256_FILE
  # little information of progress
  _echo "[info] Package zip created (${VDM_PACKAGE_ZIP_PATH})"
  # success
  return 0
}

# write the build results (manifest file and key=value outputs)
function setOutputs() {
  # the output file (GitHub Actions sets GITHUB_OUTPUT)
  local output_file="${VDM_OUTPUT_FILE:-${GITHUB_OUTPUT:-}}"
  local tag
  local version
  local pushed=false
  local status='disabled'
  local package_dir=''
  local package_xml=''
  local repository_url=''
  local extensions='[]'
  # set the version (with and without the v prefix)
  tag="${VDM_PACKAGE_VERSION:-1.0.0}"
  version="${tag/#v/}"
  # did we push to the git repository (pushed, unchanged or disabled)
  if _is_true "${VDM_PACKAGE_PUSH}"; then
    status="${VDM_REPOSITORY_STATUS:-unchanged}"
    [ "${status}" = 'pushed' ] && pushed=true
  fi
  # the package files are only available when kept
  if _is_true "${VDM_KEEP_FILES}"; then
    package_dir="${VDM_PACKAGE_DIR}"
    package_xml="${VDM_PACKAGE_XML}"
  fi
  # the repository url
  if [ -n "${VDM_PACKAGE_URL}" ] && [ -n "${VDM_PACKAGE_OWNER}" ] && [ -n "${VDM_PACKAGE_REPO}" ]; then
    repository_url="https://${VDM_PACKAGE_URL}/${VDM_PACKAGE_OWNER}/${VDM_PACKAGE_REPO}"
  fi
  # get the extensions list
  if [ -s "${VDM_FILES_JSON}" ]; then
    extensions=$(jq -sc '.' "${VDM_FILES_JSON}") || extensions='[]'
  fi
  # write the manifest file (next to the zip file)
  if [ -n "${VDM_PACKAGE_ZIP_PATH}" ]; then
    VDM_PACKAGE_MANIFEST="${VDM_PACKAGE_ZIP_PATH%.zip}.json"
    export VDM_PACKAGE_MANIFEST
    # little information of progress
    _echo "[info] Writing the package manifest (${VDM_PACKAGE_MANIFEST})..."
    jq -n \
      --arg packager "${PROGRAM_NAME} v${PROGRAM_VERSION}" \
      --arg created "$(TZ=":ZULU" date +"%Y-%m-%dT%H:%M:%SZ")" \
      --arg name "$(_human_name "${VDM_NAME}")" \
      --arg package_name "${VDM_PACKAGE_NAME}" \
      --arg code_name "${VDM_CODE_NAME}" \
      --arg version "${version}" \
      --arg tag "${tag}" \
      --arg min_joomla "${VDM_MIN_JOOMLA_VERSION}" \
      --arg max_joomla "${VDM_MAX_JOOMLA_VERSION}" \
      --arg zip "${VDM_PACKAGE_ZIP_NAME}" \
      --arg sha256 "${VDM_PACKAGE_ZIP_SHA256}" \
      --arg owner "${VDM_PACKAGE_OWNER}" \
      --arg repo "${VDM_PACKAGE_REPO}" \
      --arg branch "${VDM_PACKAGE_REPO_BRANCH}" \
      --arg url "${repository_url}" \
      --arg status "${status}" \
      --argjson pushed "${pushed}" \
      --argjson extensions "${extensions}" \
      '{
        packager: $packager,
        created: $created,
        package: {
          name: $name,
          package_name: $package_name,
          code_name: $code_name,
          version: $version,
          tag: $tag,
          min_joomla_version: $min_joomla,
          max_joomla_version: $max_joomla
        },
        zip: {name: $zip, sha256: $sha256},
        repository: {owner: $owner, repo: $repo, branch: $branch, url: $url, pushed: $pushed, status: $status},
        extensions: $extensions
      }' >"${VDM_PACKAGE_MANIFEST}" || {
      echo >&2 "[error] We could not write the package manifest (${VDM_PACKAGE_MANIFEST})."
      unset VDM_PACKAGE_MANIFEST
    }
  fi
  # we only write the outputs when we have an output file
  [ -n "${output_file}" ] || return 0
  # little information of progress
  _echo "[info] Writing the outputs to (${output_file})..."
  {
    _output 'name' "$(_human_name "${VDM_NAME}")"
    _output 'package-name' "${VDM_PACKAGE_NAME}"
    _output 'code-name' "${VDM_CODE_NAME}"
    _output 'version' "${version}"
    _output 'tag' "${tag}"
    _output 'package-dir' "${package_dir}"
    _output 'package-xml' "${package_xml}"
    _output 'package-zip' "${VDM_PACKAGE_ZIP_PATH}"
    _output 'package-zip-name' "${VDM_PACKAGE_ZIP_NAME}"
    _output 'package-zip-dir' "${VDM_PACKAGE_ZIP_DIR}"
    _output 'package-sha256' "${VDM_PACKAGE_ZIP_SHA256}"
    _output 'package-sha256-file' "${VDM_PACKAGE_ZIP_SHA256_FILE}"
    _output 'package-manifest' "${VDM_PACKAGE_MANIFEST}"
    _output 'repository-owner' "${VDM_PACKAGE_OWNER}"
    _output 'repository-repo' "${VDM_PACKAGE_REPO}"
    _output 'repository-branch' "${VDM_PACKAGE_REPO_BRANCH}"
    _output 'repository-url' "${repository_url}"
    _output 'pushed' "${pushed}"
    _output 'repository-status' "${status}"
    _output 'extensions' "${extensions}"
  } >>"${output_file}" || {
    echo >&2 "[error] We could not write the outputs to (${output_file})."
    return 32
  }
  # success
  return 0
}

# write one output value (GitHub Actions multiline format)
function _output() {
  local key="${1}"
  local value="${2}"
  local delimiter="octojpack_${RANDOM}${RANDOM}${RANDOM}"
  printf '%s<<%s\n%s\n%s\n' "${key}" "${delimiter}" "${value}" "${delimiter}"
}

# get the human readable name (resolves the language constants of the packager language)
function _human_name() {
  local value="${1}"
  if [ -n "${value}" ] && [ -n "${VDM_LANG_STRINGS[${value}]+x}" ]; then
    echo "${VDM_LANG_STRINGS[${value}]}"
  else
    echo "${value}"
  fi
}

# check that a value is a valid owner, repository or branch name (safe in paths and git urls)
function _valid_name() {
  [[ "${1}" =~ ^[A-Za-z0-9][A-Za-z0-9._-]*$ ]] && [ "${1}" != '..' ]
}

# make a value safe to use as a file or folder name (no path separators, never . or ..)
function _safe_name() {
  local value="${1}"
  value="${value//\//_}"
  value="${value//\\/_}"
  value="${value//[[:space:]]/_}"
  if [ -z "${value}" ] || [ "${value}" = '.' ] || [ "${value}" = '..' ]; then
    echo >&2 "[error] The name (${1}) can not be used as a file or folder name."
    return 12
  fi
  echo "${value}"
}

# make a path absolute (relative to the directory the program was started in)
function _abs_path() {
  case "${1}" in
  '' | /*)
    printf '%s' "${1}"
    ;;
  *)
    printf '%s/%s' "${VDM_START_DIR}" "${1}"
    ;;
  esac
}

# set an option given on the command line (and remember it, so the env files can not override it)
# the fourth argument (path) makes a relative path absolute, since the program changes directory while working
function setCliOption() {
  local name="${1}"
  local value="${2}"
  local option="${3}"
  local kind="${4:-}"
  if [ -z "${value}" ]; then
    echo "[error] \"${option}\" requires a non-empty option argument."
    exit 17
  fi
  if [ "${kind}" = 'path' ] && ! [[ "${value}" =~ ^https?: ]]; then
    value="$(_abs_path "${value}")"
  fi
  declare -g "${name}=${value}"
  CLI_OPTIONS+=("${name}=${value}")
}

# re-apply the options given on the command line (they take precedence over the env files)
function applyCliOptions() {
  local option
  for option in "${CLI_OPTIONS[@]}"; do
    declare -g "${option%%=*}=${option#*=}"
  done
}

# check if a value is true (1, true, yes, on, y)
function _is_true() {
  case "${1,,}" in
  1 | true | yes | on | y)
    return 0
    ;;
  *)
    return 1
    ;;
  esac
}

# give the echo messages
# only if not set to be quiet
function _echo() {
  if (("$QUIET" == 0)); then
    echo "$1"
  fi
}

# Unzip a zip file
function _unzip() {
  # Set some locals.
  local zip_name="${1}"
  local folder_name="${2}"

  # Unzip the contents of the `zip_name` file to the specified `folder_name`.
  # Use process substitution to pass the output of `unzip` to `cat`.
  if cat < <(unzip "${VDM_PACKAGE_SRC_DIR}/$zip_name" -d "${VDM_PACKAGE_GIT_DIR}/$folder_name") >/dev/null 2>&1; then
    _echo "[info] Successfully unzipped the package ($zip_name)"
    return 0
  fi

  # Return 1 if the unzip operation was unsuccessful.
  return 1
}

# uninstalls the octojpack program.
function runUninstall() {
  if [[ $0 -ef /usr/bin/octojpack ]] && dpkg-query -S /usr/bin/octojpack >/dev/null 2>&1; then
    printf '%s\n' 'This installation is managed by APT. Use apt to upgrade or remove octojpack.' >&2
    return 1
  fi
  # now remove the script
  if [ -f "/usr/local/bin/${PROGRAM_CODE}" ]; then
    sudo rm -f "/usr/local/bin/${PROGRAM_CODE}"
    echo "[info] ${PROGRAM_NAME} v${PROGRAM_VERSION} has been completely uninstalled."
  else
    echo "[info] ${PROGRAM_NAME} v${PROGRAM_VERSION} is not installed."
  fi
}

# check if we have project overrides for the environment variables
function getProjectEnvironment() {
  # load the config data
  VDM_CONFIG_DATA=$(cat "$VDM_PACKAGE_CONF_FILE")
  # make sure we have package details
  if [[ "${VDM_CONFIG_DATA}" =~ '"package"' ]] && [[ "${VDM_CONFIG_DATA}" =~ '"files"' ]]; then
    # little information of progress
    _echo "[info] Loading the environment variables..."
    # make configuration globally available
    export VDM_CONFIG_DATA
    # get package code_name
    getConfigValue 'VDM_CODE_NAME' '.package.code_name'
    # the tmp path to the env of this project
    tmp_path="/home/$USER/.config/${PROGRAM_CODE}/.${VDM_CODE_NAME}"
    # shellcheck disable=SC1090
    [ -f "${tmp_path}" ] && source "${tmp_path}"
    # the command line options take precedence
    applyCliOptions
    # clear this tmp out
    unset tmp_path
    # success
    return 0
  else
    # failed
    return 17
  fi
}

# updates the octojpack program to the latest version.
function runUpdate() {
  if [[ $0 -ef /usr/bin/octojpack ]] && dpkg-query -S /usr/bin/octojpack >/dev/null 2>&1; then
    printf '%s\n' 'This installation is managed by APT. Use apt to upgrade or remove octojpack.' >&2
    return 1
  fi
  # remove the current version
  if [ -f "/usr/local/bin/${PROGRAM_CODE}" ]; then
    # just backup in case of failure
    sudo mv "/usr/local/bin/${PROGRAM_CODE}" "/usr/local/bin/${PROGRAM_CODE}.bak"
  fi
  # pull the latest version. Master is always the latest
  if sudo curl --fail -L "https://raw.githubusercontent.com/octoleo/${PROGRAM_CODE}/refs/heads/${branch:-master}/src/${PROGRAM_CODE}" -o "/usr/local/bin/${PROGRAM_CODE}" 2>/dev/null; then
    # give success message
    echo "[success] Update was successful."
    # do we have a backup
    if [ -f "/usr/local/bin/${PROGRAM_CODE}.bak" ]; then
      # lets remove it now
      sudo rm -f "/usr/local/bin/${PROGRAM_CODE}.bak"
    fi
  else
    # show the error
    echo >&2 "[error] Update failed! Please try again later."
    # do we have a backup
    if [ -f "/usr/local/bin/${PROGRAM_CODE}.bak" ]; then
      # move backup back
      sudo mv "/usr/local/bin/${PROGRAM_CODE}.bak" "/usr/local/bin/${PROGRAM_CODE}"
    fi
  fi
  # always set the permission again if we have a file
  if [ -f "/usr/local/bin/${PROGRAM_CODE}" ]; then
    # the we make sure its executable
    sudo chmod +x "/usr/local/bin/${PROGRAM_CODE}"
  fi
  # always exit so the new script can load
  exit 0
}

# help message ʕ•ᴥ•ʔ
function show_help() {
  cat <<EOF
Usage: ${PROGRAM_CODE} [OPTION...]
	Options
	======================================================
   -p | --packager=<packager Name>
	Packager name
	example: ${PROGRAM_CODE} -p="Vast Development Method"
	======================================================
   -pu | --packager-url=<//packager.url>
	Packager url
	example: ${PROGRAM_CODE} -pu="https://git.vdm.dev/"
	======================================================
   -md | --main-dir=<path>
	load the main working directory
	example: ${PROGRAM_CODE} --main-dir=/src
	======================================================
   -e | --env=<file>
	load the environment variables file
	example: ${PROGRAM_CODE} --env=/src/.env
	======================================================
   --conf | --config=<path/url>
	load the configuration for the package in json format
	   file-example: src/example.json
	example: ${PROGRAM_CODE} --config=config.json
	======================================================
   -ld | --licence-dir=<path>
	load the licence directory
	example: ${PROGRAM_CODE} --licence-dir=/src/licence
	======================================================
   -t | --token=<access_token>
	load the global token
	example: ${PROGRAM_CODE} --token=xxxxxxxxxxxxxxxxxxxxxxxxx
	======================================================
   -u | --url=<gitea>
	Global url of the Gitea instance
	example: ${PROGRAM_CODE} --url="git.vdm.dev"
	======================================================
   -a | --api=<//gitea.api>
	Global api of the Gitea instance
	example: ${PROGRAM_CODE} --api="https://git.vdm.dev/api/v1"
	======================================================
   --zip
	build a zip file of the package (Joomla installable package)
	   env: VDM_PACKAGE_ZIP=1
	example: ${PROGRAM_CODE} --zip
	======================================================
   --zip-name=<file.zip>
	the file name of the package zip (default: <package_name>_<tag>.zip)
	   env: VDM_PACKAGE_ZIP_NAME
	example: ${PROGRAM_CODE} --zip-name=pkg_example_v1.0.0.zip
	======================================================
   --zip-dir=<path>
	the directory where the package zip is placed (default: <main-dir>/packages)
	   env: VDM_PACKAGE_ZIP_DIR
	example: ${PROGRAM_CODE} --zip-dir=/src/packages
	======================================================
   --no-push
	do not push the package to the git repository
	   (the repository config section becomes optional)
	   env: VDM_PACKAGE_PUSH=0
	example: ${PROGRAM_CODE} --no-push
	======================================================
   --keep-files
	keep the package build files once done (do not remove them)
	   env: VDM_KEEP_FILES=1
	example: ${PROGRAM_CODE} --keep-files
	======================================================
   -o | --output=<file>
	write the build results (names, version, paths) to a file
	   in the GitHub Actions output format (defaults to \$GITHUB_OUTPUT when set)
	   env: VDM_OUTPUT_FILE
	example: ${PROGRAM_CODE} --output=/src/octojpack.out
	======================================================
   -q | --quiet
	mute all output messages
	example: ${PROGRAM_CODE} --quiet
	======================================================
   --update
	to update your install
	example: ${PROGRAM_CODE} --update
	======================================================
   --uninstall
	to uninstall this script
	example: ${PROGRAM_CODE} --uninstall
	======================================================
   -h|--help
	display this help menu
	example: ${PROGRAM_CODE} -h
	example: ${PROGRAM_CODE} --help
	======================================================
	Options given on the command line take precedence
	over the values of the .env files.
	======================================================
			${PROGRAM_NAME} v${PROGRAM_VERSION}
	======================================================
EOF
}

# SET THE DEFAULTS #####################################
# get start time
# shellcheck disable=SC2034
START_BUILD=$(date +"%s")
# use UTC+00:00 time also called zulu
# shellcheck disable=SC2034
START_DATE=$(TZ=":ZULU" date +"%m/%d/%Y @ %R (UTC)")
CREATION_DATE=$(TZ=":ZULU" date +"%B %Y")
CREATION_YEAR=$(TZ=":ZULU" date +"%Y")

# the directory the program was started in (relative paths are resolved against it)
VDM_START_DIR="${PWD}"

# the quiet switch
QUIET="${QUIET:-0}"

# the package zip switch (build a zip file of the package)
VDM_PACKAGE_ZIP="${VDM_PACKAGE_ZIP:-0}"
# the git push switch (push the package to the git repository)
VDM_PACKAGE_PUSH="${VDM_PACKAGE_PUSH:-1}"
# the keep files switch (keep the package build files once done)
VDM_KEEP_FILES="${VDM_KEEP_FILES:-0}"

# we set the packager directorys
tmp_path="/home/$USER/${PROGRAM_CODE}"
# ALWAYS USE GLOBAL IF SET
VDM_MAIN_DIR="${VDM_MAIN_DIR:-$tmp_path}"

# we set the licenses directory
tmp_path="${VDM_MAIN_DIR}/licenses"
[ -d "$tmp_path" ] || tmp_path="/home/$USER/${PROGRAM_CODE}/licenses"
# if path not set try $PWD path
[ -d "$tmp_path" ] || tmp_path="$PWD"
# ALWAYS USE GLOBAL IF SET
VDM_LICENSE_DIR="${VDM_LICENSE_DIR:-$tmp_path}"

# the environment file variables path
tmp_path="$PWD/.env_${PROGRAM_CODE}"
# if file not set try $PWD path
[ -f "$tmp_path" ] || tmp_path="$VDM_MAIN_DIR/.env_${PROGRAM_CODE}"
# if file not set try $VDM_MAIN_DIR path
[ -f "$tmp_path" ] || tmp_path="/home/$USER/.config/${PROGRAM_CODE}/.env"
# ALWAYS USE GLOBAL IF SET
VDM_ENV_FILE_PATH="${VDM_ENV_FILE_PATH:-$tmp_path}"

# clear this tmp out
unset tmp_path

# check if we have options
while :; do
  case $1 in
  -h | --help)
    show_help # Display a usage synopsis.
    exit
    ;;
  -q | --quiet)
    QUIET=1
    CLI_OPTIONS+=("QUIET=1")
    ;;
  --uninstall)
    runUninstall
    shift
    ;;
  --update)
    runUpdate
    shift
    ;;
  -md=* | --main-dir=*)
    setCliOption VDM_MAIN_DIR "${1#*=}" '--main-dir' path
    ;;
  -e=* | --env=*)
    setCliOption VDM_ENV_FILE_PATH "${1#*=}" '--env' path
    ;;
  --conf=* | --config=*)
    setCliOption VDM_PACKAGE_CONF_FILE "${1#*=}" '--conf' path
    ;;
  -ld=* | --licence-dir=*)
    setCliOption VDM_LICENSE_DIR "${1#*=}" '--licence-dir' path
    ;;
  -p=* | --packager=*)
    setCliOption VDM_PACKAGER "${1#*=}" '--packager'
    ;;
  -pu=* | --packager-url=*)
    setCliOption VDM_PACKAGER_URL "${1#*=}" '--packager-url'
    ;;
  -t=* | --token=*)
    setCliOption VDM_GLOBAL_TOKEN "${1#*=}" '--token'
    ;;
  -a=* | --api=*)
    setCliOption VDM_GLOBAL_API "${1#*=}" '--api'
    ;;
  -u=* | --url=*)
    setCliOption VDM_GLOBAL_URL "${1#*=}" '--url'
    ;;
  -v=* | --verbosity=*)
    setCliOption VDM_VERBOSITY "${1#*=}" '--verbosity'
    ;;
  --zip)
    VDM_PACKAGE_ZIP=1
    CLI_OPTIONS+=("VDM_PACKAGE_ZIP=1")
    ;;
  --zip-name=*)
    setCliOption VDM_PACKAGE_ZIP_NAME "${1#*=}" '--zip-name'
    ;;
  --zip-dir=*)
    setCliOption VDM_PACKAGE_ZIP_DIR "${1#*=}" '--zip-dir' path
    ;;
  --no-push)
    VDM_PACKAGE_PUSH=0
    CLI_OPTIONS+=("VDM_PACKAGE_PUSH=0")
    ;;
  --keep-files)
    VDM_KEEP_FILES=1
    CLI_OPTIONS+=("VDM_KEEP_FILES=1")
    ;;
  -o=* | --output=*)
    setCliOption VDM_OUTPUT_FILE "${1#*=}" '--output' path
    ;;
  --) # End of all options.
    shift
    break
    ;;
  -?*)
    printf '[error] Unknown option: %s\n' "$1" >&2
    exit 1
    ;;
  *) # Default case: If no more options then break out of the loop.
    break
  esac
  shift
done

# load local environment variables
if [ -f "$VDM_ENV_FILE_PATH" ]; then
  # shellcheck disable=SC1090
  source "$VDM_ENV_FILE_PATH"
  # the command line options take precedence
  applyCliOptions
fi

# make the paths absolute (the program changes directory while working)
VDM_MAIN_DIR="$(_abs_path "${VDM_MAIN_DIR}")"
VDM_LICENSE_DIR="$(_abs_path "${VDM_LICENSE_DIR}")"
VDM_PACKAGE_ZIP_DIR="$(_abs_path "${VDM_PACKAGE_ZIP_DIR}")"
VDM_OUTPUT_FILE="$(_abs_path "${VDM_OUTPUT_FILE}")"

# if path not set try $PWD path (so you can open a folder that has .octojpack file and it will be loaded)
tmp_path="$PWD/.${PROGRAM_CODE}"
# if file not set try $VDM_MAIN_DIR path
[ -f "$tmp_path" ] || tmp_path="$VDM_MAIN_DIR/.${PROGRAM_CODE}"
# ALWAYS USE GLOBAL IF SET
VDM_PACKAGE_CONF_FILE=${VDM_PACKAGE_CONF_FILE:-$tmp_path}

# Check if the config file is passed as a URL
if [[ "$VDM_PACKAGE_CONF_FILE" =~ ^http: ]] || [[ "$VDM_PACKAGE_CONF_FILE" =~ ^https: ]]; then
  # Check if the URL is valid
  if curl --output /dev/null --silent --head --fail "$VDM_PACKAGE_CONF_FILE"; then
    # Create the directory for the configuration file if it doesn't exist
    mkdir -p "$HOME/.config/$PROGRAM_CODE/projects"

    # get a file name
    file_name=$(getUniqueFileName "$VDM_PACKAGE_CONF_FILE")

    # Download the configuration file
    curl --silent "$VDM_PACKAGE_CONF_FILE" -o "$HOME/.config/$PROGRAM_CODE/projects/${file_name}_conf.json"
    VDM_PACKAGE_CONF_FILE="$HOME/.config/$PROGRAM_CODE/projects/${file_name}_conf.json"
  else
    # Print an error message and exit if the URL is invalid
    echo >&2 "[error] The config file at $VDM_PACKAGE_CONF_FILE is not a valid URL. Aborting."
    exit 18
  fi
fi

# make the config path absolute (the program changes directory while working)
VDM_PACKAGE_CONF_FILE="$(_abs_path "${VDM_PACKAGE_CONF_FILE}")"

# make sure whe have a configuration file
[ -f "${VDM_PACKAGE_CONF_FILE}" ] || {
  echo >&2 "[error] The config:${VDM_PACKAGE_CONF_FILE:-empty_value} could not be found. Aborting."
  exit 18
}

# run Main ┬┴┬┴┤(･_├┬┴┬┴
main

exit 0
