#!/bin/bash

# Program name
PROGRAM_NAME="Octozipo"
PROGRAM_CODE="octozipo"
PROGRAM_VERSION="2.3.0"
PROGRAM_V="2.3"
# 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 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
}
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 awk >/dev/null 2>&1 || {
  echo >&2 "[error] We require awk for $PROGRAM_NAME v${PROGRAM_V} to work, but it's not installed.  Aborting."
  exit 1
}
command -v sed >/dev/null 2>&1 || {
  echo >&2 "[error] We require sed for $PROGRAM_NAME v${PROGRAM_V} to work, but it's not installed.  Aborting."
  exit 1
}

# main ˘Ô≈ôﺣ - The main function that controls the flow of the script
#
# This is the main function of the script, which controls the flow of execution and performs the following tasks:
#
# 1. Verifies that the root directory exists
# 2. Loops through all the zip files in the root directory
# 3. Unzips the current zip file to a random folder
# 4. Extracts package details from the unzipped folder
# 5. Checks if the repository exists on the system, and updates the existing repository if found
# 6. Sets up a new repository if it does not exist
# 7. Removes the random folder and the zip file (unless specified to keep)
# 8. Removes the repository folder (unless specified to keep)
#
# Global Variables:
#   VDM_ZIP_DIR: The root directory where the zip files are stored
#   VDM_GIT_URL: The URL of the Git repository
#   VDM_ORG: The name of the organization on the Git repository
#   VDM_REPO_NAME: The name of the repository
#   VDM_PATH_REPO: The path to the repository on the local system
#   VDM_KEEP_ZIP: A flag to indicate whether to keep the zip file after processing
#   VDM_KEEP_REPO: A flag to indicate whether to keep the repository folder after processing
#   VDM_KEEP_THIS_ONE: A flag to indicate whether to keep the current processed file
#   VDM_REPORT_FILE: The (optional) file to which the result of each package is appended
#   VDM_REPO_STATUS: The result of the last processed package (created|updated|unchanged|pending|dry-run)
#   DRY: A flag to indicate whether the script is in dry run mode
#
# Arguments:
#   None
#
# Returns:
#   None
main() {
  # make sure the root dir exist
  if [ -d "$VDM_ZIP_DIR" ]; then
    # go to folder where zip files are placed
    cd "$VDM_ZIP_DIR" || exit 3
    # check that the folder has zip files
    if [ "$(find . -maxdepth 1 -type f -name "*.zip" | wc -l)" -eq 0 ]; then
      showError "looking for zip files, since no zip files in the folder $VDM_ZIP_DIR ERROR-NR" 6
    fi
    # get all zip files
    for zip_name in *.zip; do
      # get a random folder name
      folder_name=$( getRandomName 7 )
      # unzip this zip file
      _unzip "${zip_name}" "${folder_name}" || {
        _error "[error] We encountered an error, we could not unzip ($VDM_ZIP_DIR/$zip_name) in to ($VDM_ZIP_DIR/$folder_name) ERROR-NR 6"
        # record the skipped package
        setReport "skipped" "${zip_name}" "" "" ""
        # so we skip this package
        continue
      }
      # check if we have a path
      if [ -d "${VDM_ZIP_DIR}/${folder_name}" ]; then
        # we change into the unzipped folder
        cd "${VDM_ZIP_DIR}/${folder_name}" || exit 1
        # every package sets its own result
        VDM_REPO_STATUS=''
        # get the package details
        getPackageDetails "${zip_name}" "${folder_name}"
        # check if the repo exist on our system
        if isRemoteBranch "git@${VDM_GIT_URL}:${VDM_ORG}/${VDM_REPO_NAME}.git" "${VDM_REPO_BRANCH}"; then
          # check if repo is locally found
          cd "${VDM_PATH_REPO}" >/dev/null 2>&1 || {
            _git clone "git@${VDM_GIT_URL}:${VDM_ORG}/${VDM_REPO_NAME}.git" \
              --branch "${VDM_REPO_BRANCH}" --single-branch \
              "${VDM_PATH_REPO}" -q || showPackageError "Clone Repo:(${VDM_REPO_NAME}) ERROR-NR" 7
            _echo "[info] Cloned git@${VDM_GIT_URL}:${VDM_ORG}/${VDM_REPO_NAME}.git"
          }
          # set the new files in place
          setNewFiles || showPackageError "Opening Folder:(${VDM_PATH_REPO}) ERROR-NR" 7
          # update the existing repo
          setExistingRepository || showPackageError "Update Repo:(${VDM_REPO_NAME}) ERROR-NR" 7
        else
          # create the new folder
          mkdir -p "${VDM_PATH_REPO}"
          # set the new files in place
          setNewFiles || showPackageError "Create Folder:(${VDM_PATH_REPO}) ERROR-NR" 7
          # setup the new repository
          setNewRepository || showPackageError "Setup Repo:(${VDM_REPO_NAME}) ERROR-NR" 7
        fi
        # record the result of this package
        setReport "${VDM_REPO_STATUS}" "${zip_name}" "${VDM_REPO_NAME}" "${VDM_REPO_BRANCH}" "${VDM_VERSION}"
        # remove the random folder
        rm -fr "${VDM_ZIP_DIR:?}/${folder_name:?}"
        # remove the zip file
        if $VDM_KEEP_ZIP || $VDM_KEEP_THIS_ONE; then
          _echo "[info] Did not remove ${VDM_ZIP_DIR}/${zip_name}"
        else
          rm -fr "${VDM_ZIP_DIR:?}/${zip_name:?}"
        fi
        # do not remove repo folder when (KEEP) (DRY) (ONE)
        if $VDM_KEEP_REPO || $DRY || $VDM_KEEP_THIS_ONE; then
          _echo "[info] Did not remove ${VDM_PATH_REPO}"
        else
          # remove the repo directory (we are done)
          rm -fr "${VDM_PATH_REPO:?}"
        fi
        # switch the one back
        if $VDM_KEEP_THIS_ONE; then
          VDM_KEEP_THIS_ONE=false
        fi
        _echo "================================"
      else
        showError "opening of folder $VDM_ZIP_DIR/$folder_name as it does not exist ERROR-NR" 5
      fi
    done
  else
    showError "opening of folder $VDM_ZIP_DIR as it does not exist ERROR-NR" 5
  fi
}

#####################################################################################################################VDM
######################################## Setters

# setNewRepository - Creates a new remote repository
#
# setNewRepository initializes a new local Git repository and pushes it to a remote repository. The remote repository
# is specified by the global variables `VDM_GIT_URL` and `VDM_ORG`. The repository name is specified by the global
# variable `VDM_REPO_NAME`. If the global variable `VDM_PUSH_CREATE` is set to true, the local repository will be pushed
# to the remote repository. If `VDM_PUSH_CREATE` is set to false or if `DRY` is set to true, the function will only
# initialize the local repository.
#
# Global Variables:
#   VDM_GIT_URL - the URL of the remote Git repository
#   VDM_ORG - the name of the organization on the remote Git repository
#   VDM_REPO_NAME - the name of the repository
#   VDM_PUSH_CREATE - a flag indicating whether or not to push the new repository to the remote
#   DRY - a flag indicating whether or not to perform a dry run
#
# Returns:
#   0 if the function completed successfully, 1 if an error occurred
setNewRepository() {
  # give heads up of the new repo
  _echo "[info] New repository (${VDM_GIT_URL}:${VDM_ORG}/$VDM_REPO_NAME)"
  # we initialize the git repo locally
  setGitInit || return 1
  # check if push create is allowed
  if $VDM_PUSH_CREATE; then
    # if dry we dont touch remote repo
    if $DRY; then
      _echo "[dry run] git push -u origin ${VDM_REPO_BRANCH}"
      _echo "[dry run] git push --tags"
      VDM_REPO_STATUS="dry-run"
    else
      # we push to create this repo
      _git push -u origin "${VDM_REPO_BRANCH}" || return 1
      # check if we have tags to push
      _git push --tags || return 1
      VDM_REPO_STATUS="created"
      # pushed create
      _echo "[info] Push created ($VDM_REPO_NAME v$VDM_VERSION) repository"
    fi
  else
    # give action info
    _echo "[info] When ready link and push changes to remote"
    # keep this one REPO
    VDM_KEEP_THIS_ONE=true
    VDM_REPO_STATUS="pending"
  fi
  return 0
}

# setExistingRepository - Updates an existing repository
#
# This function updates an existing repository. The function first checks if there are any changes in the repository.
# If there are no changes, the function notifies the user. If there are changes, the function creates a commit with a
# message that contains the current version number and updates the repository with these changes. If the push is
# successful, the function notifies the user. If the push is unsuccessful, the function returns an error code of 1.
#
# Global Variables:
#   VDM_REPO_NAME - The name of the repository being updated.
#   VDM_VERSION - The current version of the repository being updated.
#
# Returns:
#   0 - The function has completed successfully.
#   4 - An error occurred while creating the commit.
#   1 - An error occurred while pushing the changes.
setExistingRepository() {
  # Notifies the user that the existing repository is being updated.
  _echo "[info] Update ($VDM_REPO_NAME) existing repository"

  # Checks if there are any changes in the repository.
  if [[ -z $(git status --porcelain) ]]; then # ALTERNATIVE: if git diff-index --quiet HEAD --; then
    _echo "[info] No changes found in ($VDM_REPO_NAME v$VDM_VERSION) repository"
    VDM_REPO_STATUS="unchanged"
  else

    # set repository user details
    setUserDetails

    # get commit message
    VDM_GIT_COMMIT_MESSAGE=$(getGitCommitComment "${VDM_PATH_REPO}/CHANGELOG.md" "v${VDM_VERSION}")
    _echo "[info] Possible commit message:"
    _echo "[message]"
    _echo "${VDM_GIT_COMMIT_MESSAGE}"
    _echo "[/message]"

    # make a commit
    setGitCommit "$VDM_VERSION" "${VDM_GIT_COMMIT_MESSAGE}" || return 4

    # Pushes the changes and returns an error code of 1 if unsuccessful.
    setPushChanges || return 1

    # Record the result (nothing is pushed in a dry run).
    if $DRY; then
      VDM_REPO_STATUS="dry-run"
    else
      VDM_REPO_STATUS="updated"
    fi

    # Notifies the user that the changes have been pushed to the repository.
    _echo "[info] Pushed update to ($VDM_REPO_NAME v$VDM_VERSION) repository"
  fi

  # Return 0 if the function has completed successfully.
  return 0
}

# setNewFiles - Copies files from unzipped folder to repository folder
#
# setNewFiles copies all files from the unzipped folder to the repository folder, removing any existing files
# in the repository folder. This function changes to the repository folder and uses the 'mv' command to move
# all files from the unzipped folder to the repository folder. If the function is unable to change to the
# repository folder, an error code of 1 is returned.
#
# Global Variables:
#   VDM_PATH_REPO: the file path of the repository folder
#   VDM_PATH_ZIP: the file path of the unzipped folder
#
# Returns:
#   0 if the function has completed successfully
#   1 if the function was unable to change to the repository folder

setNewFiles() {
  # Changes to the correct directory.
  if cd "$VDM_PATH_REPO" >/dev/null 2>&1; then
    # Removes all files in the repository, except for dot folders.
    rm -rf "${VDM_PATH_REPO:?}/"*

    # Moves all files from the unzipped folder to the repository folder.
    mv "${VDM_PATH_ZIP}/"* "${VDM_PATH_REPO}"

    # Notifies the user that the files have been moved to the repository folder.
    _echo "[info] Files moved to (${VDM_PATH_REPO})"

  else
    # Returns an error code of 1 if unable to change to the repository folder.
    return 1
  fi

  # Return 0 if the function has completed successfully.
  return 0
}

# setGitInit - Initializes the Git repository or creates a new commit if changes exist
#
# setGitInit checks if the current directory is a Git repository. If it is, it checks if there are any changes in the repository.
# If there are no changes, it informs the user. If there are changes, it checks if a Git tag with the version number exists.
# If the tag does not exist or if there is no version number, it creates a commit with the "update" message.
# If the tag does exist, it creates a commit with the "update - v$VDM_VERSION" message.
# If the current directory is not a Git repository, it initializes the directory as a Git repository, creates a first commit
# with the "first commit" or "first commit - v$VDM_VERSION" message, and adds a remote origin for the Git repository.
#
# Global Variables:
#   VDM_VERSION - the version number to be used in the commit message
#   VDM_GIT_URL - the URL of the remote Git repository
#   VDM_ORG - the name of the organization that contains the remote Git repository
#   VDM_REPO_NAME - the name of the remote Git repository
#
# Returns:
#   0 - if the function has completed successfully
#   4 - if an error occurs during the creation of a commit
setGitInit() {
  # Checks if the current directory is a Git repository.
  if [ -d ".git" ]; then
    if [[ -z $(git status --porcelain) ]]; then # ALTERNATIVE: if git diff-index --quiet HEAD --; then
      # If there are no changes, inform the user.
      _echo "[info] No changes found in repository"
    else
      # set repository user details
      setUserDetails

      # get commit message
      VDM_GIT_COMMIT_MESSAGE=$(getGitCommitComment "${VDM_PATH_REPO}/CHANGELOG.md" "v${VDM_VERSION}")
      _echo "[info] Possible commit message:"
      _echo "[message]"
      _echo "${VDM_GIT_COMMIT_MESSAGE}"
      _echo "[/message]"

      # make a commit
      setGitCommit "$VDM_VERSION" "${VDM_GIT_COMMIT_MESSAGE}" || return 4
    fi
  else
    # If the current directory is not a Git repository, initialize it.
    _git init || return 4

    # we need to make sure the branch is the right name
    if [ "master" != "$VDM_REPO_BRANCH" ]; then
          git branch -m "$VDM_REPO_BRANCH"
    fi

    # set repository user details
    setUserDetails

    # Check if there is a version number.
    if [ -z "$VDM_VERSION" ]; then
      # If there is no version number, create a commit with the "first commit" message.
      # Return an error code of 4 if unsuccessful.
      setGitCommit "$VDM_VERSION" "first commit" || return 4
    else
      # If there is a version number, create a commit with the "first commit - v$VDM_VERSION" message.
      # Return an error code of 4 if unsuccessful.
      setGitCommit "$VDM_VERSION" "first commit - v$VDM_VERSION" || return 4
    fi

    # Add a remote origin for the Git repository.
    git remote add origin "git@${VDM_GIT_URL}:${VDM_ORG}/${VDM_REPO_NAME}.git"
  fi

  # Return 0 if the function has completed successfully.
  return 0
}

# Function: setUserDetails
# Purpose: Set Git user details based on environment variables
#
# Arguments:
#   None
#
# Environment Variables:
#   GIT_AUTHOR_NAME - Git author name
#   GIT_AUTHOR_EMAIL - Git author email
#   GIT_GPG_SIGN - Git GPG sign (true or false)
#   GIT_SSH_KEY_PATH - Path to the Git SSH key
#   GIT_GPG_KEY - Git GPG key
#
# Returns:
#   None
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
}

# setGitCommit - Makes a Git commit with a specified commit message and creates a Git tag
#
# setGitCommit adds all changes to the Git index, makes a Git commit with the specified commit message,
# and, if a version number is provided, creates a new Git tag for the commit. When tag signing is enabled
# in the git configuration (tag.gpgSign) a signed (annotated) tag is created with the commit message as
# the tag message, since automated environments have no editor to ask for one.
#
# Arguments:
#   1: the version number (optional)
#   2: the commit message
#
# Returns:
#   0: if the function has completed successfully
#   1: if the commit or tag creation was unsuccessful
setGitCommit() {
  # Adds all changes to the Git index.
  _git add . || return 1

  # Makes a Git commit with the specified commit message.
  _git commit -a -m "$2" || return 1

  # If a version number is provided, create a new Git tag for the commit.
  if [ -n "$1" ]; then
    # Check if the tag already exists.
    if [ "$(git tag -l "v$1")" ]; then
      # Return 0 if the function has completed successfully.
      return 0
    else
      # If the tag does not exist, create it.
      # Return an error code of 1 if the tag creation was unsuccessful.
      if [ "$(git config --bool --get tag.gpgsign 2>/dev/null)" = "true" ]; then
        # Signed tags are annotated tags, so they need a message (there is no editor in automated environments).
        _git tag -s "v$1" -m "$2" || return 1
      else
        _git tag "v$1" || return 1
      fi
      # Notify the user that the tag was added.
      _echo "[info] Added v$1 tag"
    fi
  fi

  # Return 0 if the function has completed successfully.
  return 0
}

# setPushChanges - Pushes the changes and tags to the remote repository
#
# setPushChanges tries to push the changes and tags to the remote repository. If the DRY variable is set to true,
# a message indicating that this is a dry run and no changes will be made will be printed. Otherwise, the changes
# and tags will be pushed to the remote repository. Stdout and stderr are redirected to /dev/null to suppress output.
#
# Global Variables:
#   DRY: a boolean indicating whether this is a dry run or not
#
# Arguments:
#   None
#
# Returns:
#   0 if the function has completed successfully, 1 if the push was unsuccessful
setPushChanges() {
  # If the DRY variable is set to true, print a message indicating that this is a dry run and no changes will be made.
  if $DRY; then
     _echo "[dry run] git push origin ${VDM_REPO_BRANCH}"
     _echo "[dry run] git push --tags"
  else
    # If the DRY variable is not set, try to push the changes and tags to the remote repository.
    # The git output is only shown when a push fails.
    _git push origin "${VDM_REPO_BRANCH}" || return 1
    _git push --tags || return 1
  fi

  # Return 0 if the function has completed successfully.
  return 0
}

#####################################################################################################################VDM
######################################## Getters

# Get Package Details - Retrieve information about a package
#
# This function retrieves information about a package, including the repository path, version number, and name.
# The function begins by creating a list of all XML files in the current directory and looping through each file.
# The version number and name are retrieved from the XML file if it is not an update server file.
# If a version number is not found, it is retrieved from the file name using the `getVersionNumberByFile` function.
# The name can either be retrieved from the XML file or the file name, depending on the value of the `VDM_USE_XML_NAME` variable.
# If an environment file exists for the package, the repository name is retrieved from the file.
# If a mapping exists for the repository name, it is used instead of the original name.
# Finally, the repository path for the package is set.
#
# Global Variables:
#   VDM_ZIP_DIR: the path to the directory containing the package zip files
#   VDM_USE_XML_NAME: a boolean indicating whether to use the name from the XML file or the file name
#   PROGRAM_CODE: the code used to identify the environment file
#   VDM_MAPPER_FILE_PATH: the path to the file containing the repository name mappings
#   VDM_SPACER: the character used to separate words in the repository name
#
# Arguments:
#   zip_name: the name of the zip file for the package
#   folder_name: the name of the folder containing the package
#
# Returns:
#   The function sets the following global variables:
#     VDM_PATH_ZIP: the path of the repository for the package
#     VDM_VERSION: the version number for the package
#     VDM_REPO_NAME: the repository name for the package
#     VDM_PATH_REPO: the repository path for the package
getPackageDetails() {
  # Declare local variables.
  local zip_name="${1}"
  local folder_name="${2}"
  local path_repo
  local version
  local name
  local len=100
  local file
  local v
  local n
  local e
  local p
  local env_file
  local env_name

  # Create a list of all XML files in the current directory.
  find . -type f -name '*.xml'  > tmp

  # Loop through the list of XML files.
  while IFS= read -r file
  do
    # Skip XML files named config.xml, access.xml, or default.xml.
    if [[ "$file" == *"config.xml" ]] || [[ "$file" == *"access.xml" ]] || [[ "$file" == *"default.xml" ]]; then
      continue
    fi

    # Retrieve the version number from the XML file.
    v=$(grep -o -P '(?<=\<version>).*?(?=\</version>)' "$file")

    # Retrieve the name from the XML file.
    n=$(grep -o -P '(?<=\<name>).*?(?=\</name>)' "$file")

    # Check if the file is an update server file (which should not be used).
    e=$(grep -o -P '\<extension' "$file")

    # If a version number and name have been retrieved, and the file is not an update server file, continue processing.
    if [ -n "$v" ] && [ -n "$n" ] && [ -n "$e" ]; then
      # Count the folder depth.
      # shellcheck disable=SC2001
      p=$(echo "$file" | sed 's|[^/]||g')

      # Keep the value of the shortest path.
      if [[ "${#p}" -lt $len ]]; then
        # Set the directory name.
        path_repo="$(dirname "${file}")"

        # Update the length.
        len="${#p}"

        # Set the version.
        version="$v"

        # Set the name.
        name="$n"
      fi
    fi

    # Clear variables for each loop.
    unset v
    unset n
    unset e
  done < tmp

  # Clear variables for each loop.
  rm tmp

  # Set the path of the repository for the package.
  VDM_PATH_ZIP="${VDM_ZIP_DIR}/${folder_name}${path_repo#.}"

  # If a version number was not found, get it from the file name.
  if [ -z "$version" ]; then
    VDM_VERSION=$(getVersionNumberByFile "$zip_name")
  else
    # Set the version number.
    VDM_VERSION="$version"
  fi

  # If the `VDM_USE_XML_NAME` variable is set, use the name from the XML file.
  if $VDM_USE_XML_NAME && [ -n "$name" ]; then
    name=$(getRepoName "${name}")
  else
    # Otherwise, use the name from the file name.
    name=$(getRepoName "${zip_name}")
  fi

  # Check if an environment file exists for the package.
  env_file="${VDM_ZIP_DIR}/${folder_name}/.${PROGRAM_CODE}"
  # If the environment file exists, get the repository name from the file.
  if [ -f "${env_file}" ]; then
    env_name=$(grep "^repo_name=" "${env_file}" | cut -d'=' -f2 | head -n 1)
    env_branch=$(grep "^repo_branch=" "${env_file}" | cut -d'=' -f2 | head -n 1)
  fi

  # Use the mapped repository name, if available.
  env_repo_name="${env_name:-$name}"
  VDM_REPO_NAME=$(getMapped "${env_repo_name}")
  # Use the mapped repository branch, if available.
  env_branch_name="${name}_branch"
  VDM_REPO_BRANCH=$(getMapped "${env_branch:-$env_branch_name}")
  if [ "$env_branch_name" = "$VDM_REPO_BRANCH" ]; then
      # Strings are equal, so change VDM_REPO_BRANCH to 'master'
      VDM_REPO_BRANCH="master"
  fi

  _echo "[info] name: $name"
  _echo "[info] Repo key name: $env_repo_name"
  _echo "[info] Repo name: $VDM_REPO_NAME"
  _echo "[info] Branch key name: ${env_branch:-$env_branch_name}"
  _echo "[info] Branch name: $VDM_REPO_BRANCH"
  _echo "[info] version: v${VDM_VERSION}"

  # Clear the `env_xxx` variable.
  unset env_name
  unset env_branch
  unset env_repo_name
  unset env_branch_name
  unset env_heading_line
  unset env_heading
  unset env_data_lines
  unset env_data_array

  # Set the repository path for the package.
  VDM_PATH_REPO="${VDM_ZIP_DIR}/${VDM_REPO_NAME}"
}

# isRemoteBranch - Checks if a branch exists in a remote repository
#
# isRemoteBranch asks the remote repository for the given branch. When the remote can not be reached at all
# (no access, wrong url, repository does not exist) the reason is shown, so that automated runs can be
# diagnosed, and the branch is treated as not existing.
#
# Arguments:
#   1: the remote repository url
#   2: the branch name
#
# Returns:
#   0 if the branch exists on the remote, 1 if not (or the remote is not available)
function isRemoteBranch() {
  local output
  local code

  # exit code 2 means the remote was reached, but the branch was not found
  output=$(git ls-remote --exit-code --heads "${1}" "${2}" 2>&1)
  code=$?

  if [ "${code}" -eq 0 ]; then
    return 0
  elif [ "${code}" -ne 2 ]; then
    _echo "[info] Remote repository (${1}) is not available (git exit ${code})"
    [ -n "${output}" ] && _echo "[info] ${output}"
  fi

  return 1
}

# getMapped - Gets the mapped repository name for a package
#
# getMapped takes the name of a package and returns its mapped repository name. If a mapping file exists (specified by
# the VDM_MAPPER_FILE_PATH variable), the function will look for a value in the file corresponding to the package name.
# If a value is found, it will be returned as the mapped repository name. If no mapping is found, the original package
# name will be returned.
#
# Global Variables:
#   VDM_MAPPER_FILE_PATH: the path to the mapping file
#
# Arguments:
#   prop_key: the name of the package
#
# Returns:
#   The mapped repository name, or the original name if no mapping is found.
function getMapped() {
  # Set the `prop_key` variable to the value of the first argument.
  local prop_key="${1}"
  local prop_value=""

  # If the config file exists,
  if [ -f "${VDM_MAPPER_FILE_PATH}" ]; then
    # get the value for the specified key.
    prop_value=$(grep "^${prop_key}=" "${VDM_MAPPER_FILE_PATH}" | cut -d'=' -f2 | head -n 1)
  fi

  # Return the mapped value, or the original value if no mapping is found.
  echo "${prop_value:-$prop_key}"
}

# getGitCommitComment - returns a possible comment
#
# getGitCommitComment returns a possible comment that can be used in the commit message
#
# Arguments:
#   1: the path to the changelog file
#   2: the current version
#
# Returns:
#   comment string
function getGitCommitComment() {
  local file_path="$1"
  local current_version="$2"
  local message
  local version_line
  local version
  local message_lines
  local cleaned_lines
  local formatted_lines

  # default message
  message="Release of ${current_version}"

  # if version tag could not be found
  if [ -z "$current_version" ]; then
    message="Update"
  # If tag already exist
  elif git rev-parse --is-inside-work-tree > /dev/null 2>&1 && git tag -l "$current_version" | grep -q "^$current_version$"; then
    message="Update on $current_version (changes towards the next release)\n\nHere's an update on the current version, which includes changes towards the next release still in development."
  # if file path exist and the tag was never set before
  elif [ -f "${file_path}" ]; then
    # Use grep to find the line number of the first heading/version
    version_line=$(grep -n "^#" "$file_path" | head -n 1 | cut -d: -f1)
    # Extract the first heading/version and assign it to a variable
    version=$(sed -n "${version_line}p" "$file_path" | sed -e 's/^#\+ *//' -e 's/^[[:space:]]*//' -e 's/^-* \?//' -e 's/[[:space:]]*$//')
    # Use awk to extract the message lines after the first header, but stop at the next header or an empty line
    message_lines=$(awk -v start=$((version_line + 1)) 'NR > start && (/^#/ || !NF) {exit} NR > start {print}' "$file_path")
    cleaned_lines=$(echo "$message_lines" | sed -e '/^[[:space:]]*$/d' -e 's/^[[:space:]]*//' -e 's/^-* \?//' -e 's/[[:space:]]*$//' -e 's/\.*$//' )
    formatted_lines=$(echo "$cleaned_lines" | awk '{printf "%s%s",(NR>1?". ":""),$0} END{printf ".\n"}')

    # check if this is the same version as the current version
    if [ "$current_version" = "$version" ]; then
      message="Release of ${current_version}\n\n${formatted_lines}"
    fi
  fi

  echo -e "${message}"
}

# getRandomName - returns a random string
#
# getRandomName returns a random string generated by a simple basic random function.
# The string consists of characters from the set 'A-HJ-NP-Za-km-z'.
# The length of the returned string can be specified as an argument, with a default length of 128.
#
# Arguments:
#   1: (optional) the desired length of the returned string
#
# Returns:
#   a random string with the specified length
function getRandomName() {
  # simple basic random
  head -c "${1:-16}" < <(tr -dc 'A-HJ-NP-Za-km-z' </dev/urandom)
}

# getRepoName - Get the repository name for a package.
#
# getRepoName processes the name of a package to determine the repository name that should be used.
# The process involves removing the Joomla version and file extension, removing version information,
# converting to lowercase, replacing spaces and dashes with the specified spacer, and removing
# any non-safe URL characters. The final result is either the original name, or the mapped repository
# name if a mapping is found in the mapper file.
#
# Arguments:
#   ${1}: The name of the package.
#
# Returns:
#   The processed repository name for the package.
function getRepoName() {
  # Set the `name` variable to the value of the first argument.
  local name="${1}"

  # Remove the Joomla version from the file name if set.
  name="${name//__J3/}"
  name="${name//__J4/}"

  # Convert the name to lowercase.
  name="${name,,}"

  # Trim the '.zip' extension from the name.
  name="${name%%.zip}"

  # Get version variation.
  tmp_v_underscore="${VDM_VERSION//./_}"
  tmp_v_dash="${VDM_VERSION//./\-}"

  # Remove the version from the name.
  name="${name//v$VDM_VERSION/ }"
  name="${name//v$tmp_v_underscore/ }"
  name="${name//v$tmp_v_dash/ }"

  # Remove all non-safe URL characters from the name.
  name="${name//[^a-z0-9_\- ]/ }"

  # Convert all underscores to spaces.
  name="${name//_/ }"

  # Convert all dashes to spaces.
  name="${name//\-/ }"

  # Remove all double spaces.
  name=$(echo "${name}" | tr -s "[:blank:]" | xargs < <(cat))

  # Convert all spaces to the specified spacer.
  name="${name//[[:space:]]/$VDM_SPACER}"

  # Return the processed name.
  echo "${name}"
}


# getVersionNumberByFile - Extracts the version number from the file name
#
# getVersionNumberByFile takes the name of a zip file as an argument and returns the version number
# contained within the file name. The version number is extracted by first removing the '.zip' extension,
# then removing any text before and after the version number, and finally converting any '-' or '_' characters
# within the version number to '.'. If the version number cannot be extracted from the file name, the default
# version number '1.0.0' is returned.
#
# Arguments:
#   1: the file name from which to extract the version number
#
# Returns:
#   The extracted version number, or "1.0.0" if a version number cannot be found
function getVersionNumberByFile() {
  local version="${1}"
  version=$(leftStrip "$version" "*-v")
  version=$(leftStrip "$version" "*_v")
  version=$(rightStrip "$version" ".zip")
  version=${version//-/\.}
  version=${version//_/\.}
  version=$(rightStrip "$version" "..*")
  # shellcheck disable=SC2001
  version=$(echo "$version" | sed 's/[^0-9.]//g')
  version=$(leftStrip "$version" "..")
  # if we have numbers
  if [[ "$version" =~ [0-9] ]]; then
    echo "$version"
  else
    echo "1.0.0"
  fi
}

#####################################################################################################################VDM
######################################## General Methods

# rightStrip - Trims a specified pattern from the end of a string
#
# The `rightStrip` function takes two arguments: a string and a pattern. It trims the specified pattern from the end of the string
# and returns the modified string.
#
# Arguments:
#   $1: A string to be modified.
#   $2: A pattern to be trimmed from the end of the string.
#
# Returns:
#   The modified string.

function rightStrip() {
  # Usage: rightStrip "string" "pattern"
  printf '%s\n' "${1%%"$2"}"
}

# leftStrip - Removes the specified pattern from the start of a string
#
# leftStrip takes a string as the first argument and a pattern as the second argument. It removes the specified pattern from the start of the string and returns the modified string.
#
# Usage:
#   leftStrip "string" "pattern"
#
# Arguments:
#   string: the input string to be modified
#   pattern: the pattern to be removed from the start of the string
#
# Returns:
#   The modified string with the pattern removed from the start
function leftStrip() {
  # Usage: leftStrip "string" "pattern"
  printf '%s\n' "${1##"$2"}"
}

# getAbsPath - Returns the absolute path of a directory or file
#
# getAbsPath resolves the given path to an absolute path, since the script changes directories while
# processing packages. A path that does not exist is returned unchanged.
#
# Arguments:
#   $1: the path to resolve
#
# Returns:
#   The absolute path (or the given path when it does not exist)
function getAbsPath() {
  local path="${1}"
  if [ -d "${path}" ]; then
    (cd "${path}" && pwd)
  elif [ -f "${path}" ]; then
    echo "$(cd "$(dirname "${path}")" && pwd)/$(basename "${path}")"
  else
    echo "${path}"
  fi
}

# _git - Runs a git command quietly, showing its output only when it fails
#
# _git runs the given git command and captures its output. When the command fails the exit code and the
# captured output are shown as an error, so that failures (authentication, missing repositories, signing
# problems) can be diagnosed in automated environments.
#
# Arguments:
#   $@: the git command and its arguments
#
# Returns:
#   The exit code of the git command
function _git() {
  local output
  local code

  output=$(git "$@" 2>&1)
  code=$?

  if [ "${code}" -ne 0 ]; then
    _error "[error] git ${1} failed (exit ${code})"
    [ -n "${output}" ] && _error "${output}"
  fi

  return "${code}"
}

# setReport - Appends the result of a package to the report file
#
# setReport appends one tab separated line to the report file (when VDM_REPORT_FILE is set), so that other
# tools (like a workflow) can act on the result of each package.
#
# Columns:
#   status, zip file, git url, org, repository, branch, version
#
# Arguments:
#   $1: the status (created|updated|unchanged|pending|dry-run|skipped|failed)
#   $2: the zip file name
#   $3: the repository name
#   $4: the branch name
#   $5: the version
#
# Returns:
#   None
function setReport() {
  if [ -n "${VDM_REPORT_FILE}" ]; then
    printf '%s\t%s\t%s\t%s\t%s\t%s\t%s\n' "${1}" "${2}" "${VDM_GIT_URL}" "${VDM_ORG}" "${3}" "${4}" "${5}" >> "${VDM_REPORT_FILE}"
  fi
}

# This function unzips the package located in the `VDM_ZIP_DIR` directory to the specified folder.
#
# The output of unzip is only shown when the package could not be unzipped. An exit code of 1 from unzip
# means it finished with warnings, which is still treated as a success.
#
# Arguments:
#   $1: the name of the zip file
#   $2: the name of the folder to which the contents of the zip file will be extracted
#
# Returns:
#   0 if the unzip operation was successful, 1 if the unzip operation was unsuccessful
function _unzip() {
  # Set some locals.
  local zip_name="${1}"
  local folder_name="${2}"
  local output
  local code

  # Unzip the contents of the `zip_name` file to the specified `folder_name`.
  output=$(unzip "$VDM_ZIP_DIR/$zip_name" -d "$VDM_ZIP_DIR/$folder_name" 2>&1)
  code=$?

  if [ "${code}" -eq 0 ] || [ "${code}" -eq 1 ]; then
    _echo "[info] Successfully unzipped the package ($zip_name)"
    return 0
  fi

  # Show why the package could not be unzipped, and remove what was extracted.
  _error "[error] unzip failed (exit ${code}) for ($zip_name)"
  [ -n "${output}" ] && _error "${output}"
  rm -fr "${VDM_ZIP_DIR:?}/${folder_name:?}"

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

# _echo - outputs a message to the console if the QUIET variable is not set
#
# _echo outputs the message in its first argument to the console if the QUIET variable is not set. If QUIET is set, the
# message will not be output.
#
# Arguments:
#   1. A string message to be output to the console
#
# Returns:
#   None

function _echo() {
  if ! $QUIET; then
    echo "$1"
  fi
}

# _error - outputs an error message to stderr (also when the QUIET variable is set)
#
# Arguments:
#   1. A string message to be output to stderr
#
# Returns:
#   None
function _error() {
  echo >&2 "$1"
}

# showError - Show error message and exit with specified code
#
# showError displays an error message indicating the line number and file where the error occurred. It then exits the
# script with the specified exit code.
#
# Arguments:
#   $1: the name of the file where the error occurred
#   $2: the exit code to use when exiting the script
#
# Returns:
#   None, the function will exit the script with the specified exit code
function showError() {
  _error "[error] We encountered an error on $1:$2"
  exit "$2"
}

# showPackageError - Record the failure of the current package and exit with specified code
#
# showPackageError adds a failed line for the package being processed to the report file and then
# shows the error message and exits the script with the specified exit code.
#
# Arguments:
#   $1: the error message
#   $2: the exit code to use when exiting the script
#
# Returns:
#   None, the function will exit the script with the specified exit code
function showPackageError() {
  setReport "failed" "${zip_name}" "${VDM_REPO_NAME}" "${VDM_REPO_BRANCH}" "${VDM_VERSION}"
  showError "$1" "$2"
}

# Function to uninstall the program
#
# This function checks if the script "/usr/local/bin/${PROGRAM_CODE}" exists,
# and if it does, it will remove the file and print a message indicating that
# the program "${PROGRAM_NAME} v${PROGRAM_VERSION}" has been uninstalled.
# If the file does not exist, it will print a message indicating that the program
# is not installed.
#
# Input:
#   - None
#
# Output:
#   - None
function runUninstall() {
  if [[ $0 -ef /usr/bin/octozipo ]] && dpkg-query -S /usr/bin/octozipo >/dev/null 2>&1; then
    printf '%s\n' 'This installation is managed by APT. Use apt to upgrade or remove octozipo.' >&2
    return 1
  fi
  # Check if the script "/usr/local/bin/${PROGRAM_CODE}" exists.
  if [ -f "/usr/local/bin/${PROGRAM_CODE}" ]; then
    # Remove the script "/usr/local/bin/${PROGRAM_CODE}".
    sudo rm -f "/usr/local/bin/${PROGRAM_CODE}"
    # Print a message indicating that the program has been uninstalled.
    _echo "[info] ${PROGRAM_NAME} v${PROGRAM_VERSION} has been completely uninstalled."
  else
    # Print a message indicating that the program is not installed.
    echo "[info] ${PROGRAM_NAME} v${PROGRAM_VERSION} is not installed."
  fi
}

# Function to update the script with the latest version
#
# This function updates the current script to the latest version.
#
# First, it will backup the current version of the script by moving
# it to a file with a ".bak" extension.
#
# Then, it will use curl to download the latest version of the script
# from the specified repository. The latest version is always stored
# in the "master" branch, unless a different branch is specified.
#
# If the update is successful, the backup file will be deleted.
# If the update fails, the backup file will be moved back to its
# original location.
#
# Finally, the permissions for the script will be set to make it
# executable, and the script will exit.
function runUpdate() {
  if [[ $0 -ef /usr/bin/octozipo ]] && dpkg-query -S /usr/bin/octozipo >/dev/null 2>&1; then
    printf '%s\n' 'This installation is managed by APT. Use apt to upgrade or remove octozipo.' >&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
}

# set the defaults (the string settings can also be set with environment variables)
: "${VDM_ZIP_DIR:=$PWD}"
: "${VDM_ORG:=joomla}"
: "${VDM_GIT_URL:=git.vdm.dev}"
: "${VDM_SPACER:=-}"
: "${VDM_GIT_DATE:=}"
: "${VDM_REPORT_FILE:=}"
VDM_GIT_COMMIT_MESSAGE=''
VDM_PUSH_CREATE=false
VDM_USE_XML_NAME=false
VDM_KEEP_ZIP=false
VDM_KEEP_REPO=false
VDM_KEEP_THIS_ONE=false
VDM_REPO_STATUS=''
DRY=false
QUIET=false
DEBUG=false
GIT_DATE_FORMAT="%b %e %X %Y %z"

# load the access token
VDM_ACCESS_TOKEN="${SETUP_TOKEN:-}"

# help message ʕ•ᴥ•ʔ
function show_help() {
  cat <<EOF
Usage: ${PROGRAM_CODE} [OPTION...]
	Options
	======================================================
   -o | --org=[ORG]
	directory of the org/user repository
	default: joomla
	example: ${PROGRAM_CODE} -o=joomla
	example: ${PROGRAM_CODE} --org=joomla
	======================================================
   -z | --zip-dir=<full-path-to-directory>
	full path to directory of the zip files
	default: $PWD
	example: ${PROGRAM_CODE} -z=/home/username/zipfiles
	example: ${PROGRAM_CODE} --zip-dir=/home/username/zipfiles
	======================================================
   -g | --git-url=<url>
	git remote repository base url
	default: git.vdm.dev
	example: ${PROGRAM_CODE} -g=git.vdm.dev
	example: ${PROGRAM_CODE} --git-url=git.vdm.dev
	======================================================
   -m | --mapper=<file>
	load the mapping file
	that convert zip names to repo names
	example: ${PROGRAM_CODE} --mapper=/src/.mapper
	======================================================
   -e | --env=<file>
	load the environment variables file
	example: ${PROGRAM_CODE} --env=/src/.env
	======================================================
   -p | --push-create
	switch to try push create new repositories
	this may not work with github
	example: ${PROGRAM_CODE} -p
	example: ${PROGRAM_CODE} --push-create
	======================================================
   -s | --spacer=<char>
	set the spacer used in repo name
	default: -
	example: ${PROGRAM_CODE} -s _
	example: ${PROGRAM_CODE} --spacer=_
	======================================================
   --git-date=<date>
	set the git commit date
	default: Actual Date
	example: ${PROGRAM_CODE} --git-date="Feb 14 03:18:31"
	======================================================
   --report=<file>
	write a tab separated report line per package
	(status, zip, git url, org, repo, branch, version)
	example: ${PROGRAM_CODE} --report=/tmp/octozipo.tsv
	======================================================
   --keep-repo
	switch to keep the repository directory
	example: ${PROGRAM_CODE} --keep-repo
	======================================================
   --keep-zip
	switch to keep the zip file
	example: ${PROGRAM_CODE} --keep-zip
	======================================================
   --use-xml-name
	use the name found in the xml as the repository name
	example: ${PROGRAM_CODE} --use-xml-name
	======================================================
   -d | --dry
	dry run of the program
	example: ${PROGRAM_CODE} --dry
	======================================================
   -q | --quiet
	mute all output messages
	example: ${PROGRAM_CODE} --quiet
	======================================================
   --debug
	to print out all config details
	example: ${PROGRAM_CODE} --debug
	======================================================
   --update
	to update your install
	example: ${PROGRAM_CODE} --update
	======================================================
   -t | --access-token [********token**********]
	token needed to access private repo for update
	example: ${PROGRAM_CODE} --access-token='********token**********'
	======================================================
   --uninstall
	to uninstall this script
	example: ${PROGRAM_CODE} --uninstall
	======================================================
   -h|--help
	display this help menu
	example: ${PROGRAM_CODE} -h
	example: ${PROGRAM_CODE} --help
	======================================================
			${PROGRAM_NAME} v${PROGRAM_VERSION}
	======================================================
EOF
}

# check if we have options
while :; do
  case $1 in
  -h | --help)
    show_help # Display a usage synopsis.
    exit
    ;;
  -q | --quiet)
    QUIET=true
    ;;
  -d | --dry)
    DRY=true
    ;;
  --keep-zip)
    VDM_KEEP_ZIP=true
    ;;
  --keep-repo)
    VDM_KEEP_REPO=true
    ;;
  --use-xml-name)
    VDM_USE_XML_NAME=true
    ;;
  -p | --push-create)
    VDM_PUSH_CREATE=true
    ;;
  -z | --zip-dir) # Takes an option argument; ensure it has been specified.
    if [ "$2" ]; then
      VDM_ZIP_DIR=$2
      shift
    else
      _error '[error] "--zip-dir" requires a non-empty option argument.'
      exit 17
    fi
    ;;
  -z=?* | --zip-dir=?*)
    VDM_ZIP_DIR=${1#*=} # Delete everything up to "=" and assign the remainder.
    ;;
  -z= | --zip-dir=) # Handle the case of an empty --packages=
    _error '[error] "--zip-dir=" requires a non-empty option argument.'
    exit 17
    ;;
  -g | --git-url) # Takes an option argument; ensure it has been specified.
    if [ "$2" ]; then
      VDM_GIT_URL=$2
      shift
    else
      _error '[error] "--git-url" requires a non-empty option argument.'
      exit 17
    fi
    ;;
  -g=?* | --git-url=?*)
    VDM_GIT_URL=${1#*=} # Delete everything up to "=" and assign the remainder.
    ;;
  -g= | --git-url=) # Handle the case of an empty --packages=
    _error '[error] "--git-url=" requires a non-empty option argument.'
    exit 17
    ;;
  -o | --org) # Takes an option argument; ensure it has been specified.
    if [ "$2" ]; then
      VDM_ORG=$2
      shift
    else
      _error '[error] "--org" requires a non-empty option argument.'
      exit 17
    fi
    ;;
  -o=?* | --org=?*)
    VDM_ORG=${1#*=} # Delete everything up to "=" and assign the remainder.
    ;;
  -o= | --org=) # Handle the case of an empty --packages=
    _error '[error] "--org=" requires a non-empty option argument.'
    exit 17
    ;;
  --git-date) # Takes an option argument; ensure it has been specified.
    if [ "$2" ]; then
      VDM_GIT_DATE=$2
      shift
    else
      _error '[error] "--git-date" requires a non-empty option argument.'
      exit 17
    fi
    ;;
  --git-date=?*)
    VDM_GIT_DATE=${1#*=} # Delete everything up to "=" and assign the remainder.
    ;;
  --git-date=) # Handle the case of an empty --packages=
    _error '[error] "--git-date=" requires a non-empty option argument.'
    exit 17
    ;;
  -s | --spacer) # Takes an option argument; ensure it has been specified.
    if [ "$2" ]; then
      VDM_SPACER=$2
      shift
    else
      _error '[error] "--spacer" requires a non-empty option argument.'
      exit 17
    fi
    ;;
  -s=?* | --spacer=?*)
    VDM_SPACER=${1#*=} # Delete everything up to "=" and assign the remainder.
    ;;
  -s= | --spacer=) # Handle the case of an empty --packages=
    _error '[error] "--spacer=" requires a non-empty option argument.'
    exit 17
    ;;
  -e | --env) # Takes an option argument; ensure it has been specified.
    if [ "$2" ]; then
      VDM_ENV_FILE_PATH=$2
      shift
    else
      _error '[error] "--env" requires a non-empty option argument.'
      exit 17
    fi
    ;;
  -e=?* | --env=?*)
    VDM_ENV_FILE_PATH=${1#*=} # Delete everything up to "=" and assign the remainder.
    ;;
  -e= | --env=) # Handle the case of an empty --packages=
    _error '[error] "--env=" requires a non-empty option argument.'
    exit 17
    ;;
  -m | --mapper) # Takes an option argument; ensure it has been specified.
    if [ "$2" ]; then
      VDM_MAPPER_FILE_PATH=$2
      shift
    else
      _error '[error] "--mapper" requires a non-empty option argument.'
      exit 17
    fi
    ;;
  -m=?* | --mapper=?*)
    VDM_MAPPER_FILE_PATH=${1#*=} # Delete everything up to "=" and assign the remainder.
    ;;
  -m= | --mapper=) # Handle the case of an empty --packages=
    _error '[error] "--mapper=" requires a non-empty option argument.'
    exit 17
    ;;
  -t | --access-token) # Takes an option argument; ensure it has been specified.
    if [ "$2" ]; then
      VDM_ACCESS_TOKEN=$2
      shift
    else
      _error '[error] "--token" requires a non-empty option argument.'
      exit 17
    fi
    ;;
  -t=?* | --access-token=?*)
    VDM_ACCESS_TOKEN=${1#*=} # Delete everything up to "=" and assign the remainder.
    ;;
  --report) # Takes an option argument; ensure it has been specified.
    if [ "$2" ]; then
      VDM_REPORT_FILE=$2
      shift
    else
      _error '[error] "--report" requires a non-empty option argument.'
      exit 17
    fi
    ;;
  --report=?*)
    VDM_REPORT_FILE=${1#*=} # Delete everything up to "=" and assign the remainder.
    ;;
  --report=) # Handle the case of an empty --report=
    _error '[error] "--report=" requires a non-empty option argument.'
    exit 17
    ;;
  --debug)
    DEBUG=true
    ;;
  --uninstall)
    runUninstall
    shift
    ;;
  --update)
    runUpdate
    ;;
  *) # Default case: No more options, so break out of the loop.
    break ;;
  esac
  shift
done

# the environment variables path
tmp_path="$VDM_ZIP_DIR/.${PROGRAM_CODE}"
# if path not set try global path
[ -f "$tmp_path" ] || tmp_path="${HOME:-/home/$USER}/.config/${PROGRAM_CODE}/.env"
: "${VDM_ENV_FILE_PATH:=$tmp_path}"
# add env to system
if [ -f "${VDM_ENV_FILE_PATH}" ]; then
  # shellcheck disable=SC1090
  source "${VDM_ENV_FILE_PATH}"
fi
# the mapper path
tmp_path="$VDM_ZIP_DIR/.${PROGRAM_CODE}.mapper"
# if path not set try global path
[ -f "$tmp_path" ] || tmp_path="${HOME:-/home/$USER}/.config/${PROGRAM_CODE}/.mapper"
: "${VDM_MAPPER_FILE_PATH:=$tmp_path}"
# done with the tmp_path
unset tmp_path

# we change directories while processing, so all paths must be absolute
VDM_ZIP_DIR=$(getAbsPath "$VDM_ZIP_DIR")
VDM_MAPPER_FILE_PATH=$(getAbsPath "$VDM_MAPPER_FILE_PATH")

# start a new report file (when set)
if [ -n "$VDM_REPORT_FILE" ]; then
  : > "$VDM_REPORT_FILE" || showError "creating the report file ($VDM_REPORT_FILE) ERROR-NR" 8
  VDM_REPORT_FILE=$(getAbsPath "$VDM_REPORT_FILE")
fi

# set the git date
if [ -n "$VDM_GIT_DATE" ]; then
        # make sure the format is correct
        GIT_AUTHOR_DATE=$( date --date="$VDM_GIT_DATE" +"$GIT_DATE_FORMAT")
else
        # set today's date
        GIT_AUTHOR_DATE=$( date +"$GIT_DATE_FORMAT")
fi
# set the git committer date
GIT_COMMITTER_DATE="$GIT_AUTHOR_DATE"

# now make globally available to git
export GIT_AUTHOR_DATE
export GIT_COMMITTER_DATE

# dynamic defaults
VDM_PATH_REPO=''
VDM_PATH_ZIP=''
VDM_VERSION=''
VDM_REPO_NAME=''
VDM_REPO_BRANCH=''

# debug config values
if $DEBUG; then
# show globals
cat <<EOF
	Options: VALUES
	======================================================
   -o | --org=[ORG]
	VALUE: $VDM_ORG
	======================================================
   -z | --zip-dir=<full-path-to-directory>
	VALUE: $VDM_ZIP_DIR
	======================================================
   -g | --git-url=<url>
	VALUE: $VDM_GIT_URL
	======================================================
   -m | --mapper=<file>
	VALUE: $VDM_MAPPER_FILE_PATH
	======================================================
   -e | --env=<file>
	VALUE: $VDM_ENV_FILE_PATH
	======================================================
   -p | --push-create
	VALUE: $VDM_PUSH_CREATE
	======================================================
   -s | --spacer=<char>
	VALUE: $VDM_SPACER
	======================================================
   --git-date=<date>
	VALUE: $VDM_GIT_DATE
	======================================================
   --report=<file>
	VALUE: $VDM_REPORT_FILE
	======================================================
   --keep-repo
	VALUE: $VDM_KEEP_REPO
	======================================================
   --keep-zip
	VALUE: $VDM_KEEP_ZIP
	======================================================
   --use-xml-name
	VALUE: $VDM_USE_XML_NAME
	======================================================
   -d | --dry
	VALUE: $DRY
	======================================================
   -q | --quiet
	VALUE: $QUIET
	======================================================
   --debug
	VALUE: $DEBUG
	======================================================
   -t | --token=[token]
	VALUE: $VDM_ACCESS_TOKEN
	======================================================
			${PROGRAM_NAME} v${PROGRAM_VERSION}
	======================================================
EOF
  exit 0
fi

# run main
main

# clear globals
unset GIT_AUTHOR_DATE
unset GIT_COMMITTER_DATE
