#!/usr/bin/env bash
# shellcheck disable=2016 disable=1091 disable=2059

version="2023-11-21"

# Notes:
#   2023-11-21 - Update MariaDB default to 11.2, add support for 11.3
#   2023-08-21 - Update MariaDB default to 11.1, add support for 11.2
#   2023-08-14 - Add Debian 12 Bookworm
#   2023-06-09 - Update MariaDB default to 11.0, add support for 11.1
#   2023-06-08 - Fix for uname reporting alternate arch names
#   2023-02-16 - Update MariaDB default to 10.11, add support for 11.0
#   2023-01-23 - Add to the error message about missing/wrong version
#   2023-01-23 - Better support for setting up old repositories
#   2022-11-17 - Update MariaDB default to 10.10, add support for 10.11
#   2022-09-12 - Minor updates to some info messages
#   2022-08-22 - Fix 10.10 issue with Ubuntu 22.04 and Debian 11
#   2022-08-15 - Update MariaDB to 10.9, add support for 10.10
#   2022-08-09 - Add RHEL/Rocky 9
#   2022-07-27 - Remove Debian 9 Stretch
#   2022-06-14 - Add --skip-verify option for skipping version verification
#   2022-06-13 - Handle case where invalid os+server combo, but Maxscale OK
#   2022-06-06 - Add function to test for known invalid os+server combinations
#   2022-06-03 - Update MariaDB to 10.8, add support for 10.9
#   2022-06-02 - Look up current MariaDB versions
#   2022-06-01 - Add --skip-eol-check and --skip-os-eol-check options for
#                testing old eol versions of mariadb
#   2022-05-31 - move all repos to dlm.mariadb.com
#   2022-05-03 - Add Rocky 8 to usage/help output, Remove CentOS 8
#   2022-04-21 - add Ubuntu 22.04 LTS "jammy"
#   2022-02-08 - Adjust repo pinning for Ubuntu/Debian, update MariaDB to 10.7
#   2022-01-31 - Verify that server version is valid
#   2022-01-18 - Add aarch64 RHEL/SLES repositories
#   2021-12-10 - Update keyring URL
#   2021-11-18 - Update default URL of script
#   2021-11-08 - Add support for 10.7
#   2021-08-02 - Add Debian 11 Bullseye & aarch64/arm64 MaxScale repositories
#   2021-07-30 - Remove Ubuntu 16.04 Xenial
#   2021-07-06 - Update MariaDB to 10.6
#   2021-06-28 - Fix warnings with debug repositories on Ubuntu 18.04 Bionic
#   2021-06-24 - MDEV-25991, adjust apt-transport-https dependency
#   2021-06-21 - Download repo keys to pki folder on RHEL, SLES
#   2021-06-09 - Limit deb repos to amd64,arm64 architectures
#   2021-06-07 - MDEV-25805 fix detection for Rocky and Alma Linux 8
#   2021-06-01 - Clean Package Cache after yum/dnf/zyp repository configuration
#   2021-05-26 - Fix URL handling, remove unneeded warning
#   2021-05-21 - Set 10.6 repos to pull from the correct place
#   2021-05-03 - Fix MaxScale repository paths, add --skip-check-installed flag
#   2021-03-04 - Add chmod step to ensure apt can read the keyring
#   2021-02-12 - Include dbgsym ddeb packages for Ubuntu
#   2021-01-26 - Validate manually supplied --os-type and --os-version
#   2021-01-22 - Remove ambiguous $releasever and $basearch from rhel repo
#   2021-01-22 - Remove ambiguous $basearch from sles repo
#   2021-01-14 - Add --version flag
#   2020-12-16 - Fix issue with detecting CentOS 8.3+
#   2020-12-16 - remove CentOS 6, deprecated as of Nov 2020
#   2020-12-07 - remove Debian 8 Jessie, deprecated as of Jun 2020
#   2020-10-15 - Add check_installed function to ensure script can run
#   2020-10-15 - Update MariaDB MaxScale to use CDN
#   2020-10-15 - Change default MaxScale to 'latest'
#   2020-09-11 - Update default MaxScale version to 2.5
#   2020-06-25 - Update MariaDB to 10.5, also deprecate Ubuntu 14.04 'trusty'
#   2020-05-12 - update curl command to correctly handle CDN redirects
#   2020-03-27 - add Ubuntu 20.04 "focal"
#   2020-01-22 - add "module_hotfixes = 1" to RHEL/CentOS 8 config (MDEV-20673)
#   2020-01-22 - update msg strings for better output and consistency
#   2020-01-08 - add autorefresh=1 to sles repo configs
#   2019-12-04 - add RHEL 8, and CentOS 8
#   2019-09-25 - add Debian 10 "buster"
#   2019-09-25 - MDEV-20654 - change gpg key importing
#   2019-09-24 - Update to MaxScale Version 2.4
#   2019-06-18 - Update to MariaDB 10.4
#   2018-12-24 - Update to MaxScale Version 2.3

# This script will identify the OS distribution and version, make sure it's
# supported, and set up the appropriate MariaDB software repositories.

supported="# The MariaDB Repository only supports these distributions:
#    * RHEL/Rocky 8 & 9 (rhel)
#    * RHEL/CentOS 7 (rhel)
#    * Ubuntu 18.04 LTS (bionic), 20.04 LTS (focal), & 22.04 LTS (jammy)
#    * Debian 10 (buster), Debian 11 (bullseye), and Debian 12 (bookworm)
#    * SLES 12 & 15 (sles)"

otherplatforms="# See https://mariadb.com/kb/en/mariadb/mariadb-package-repository-setup-and-usage/#platform-support"

url_base="dlm.mariadb.com"
url_mariadb_repo="https://${url_base}/repo/mariadb-server"
mariadb_server_version=mariadb-11.2
mariadb_server_version_real=mariadb-11.2
mariadb_maxscale_version=latest
write_to_stdout=0
skip_key_import=0
skip_maxscale=0
skip_server=0
skip_tools=0
skip_verify=0
skip_check_installed=0
skip_eol_check=0
skip_os_eol_check=0
extra_options=""
version_info=""

usage="Usage: curl -LsS https://r.mariadb.com/downloads/mariadb_repo_setup | bash -s -- [OPTIONS]

    https://mariadb.com/kb/en/mariadb/mariadb-package-repository-setup-and-usage/

$supported

Options:
    --help                  Display this help and exit.

    --version               Output the script version and exit.

    --mariadb-server-version=<version>
                            Override the default MariaDB Server version.
                            By default, the script will use '$mariadb_server_version'.

    --mariadb-maxscale-version=<version>
                            Override the default MariaDB MaxScale version.
                            By default, the script will use '$mariadb_maxscale_version'.

    --os-type=<type>        Override detection of OS type. Acceptable values
                            include 'debian', 'ubuntu', 'rhel', and 'sles'.

    --os-version=<version>  Override detection of OS version. Acceptable values
                            depend on the OS type you specify.

    --arch=<architecture>   Override detection of CPU architecture. Acceptable
                            values are 'x86_64', 'aarch64', 'amd64', & 'arm64'.

    --skip-key-import       Skip importing GPG signing keys.

    --skip-maxscale         Skip the 'MaxScale' repository.

    --skip-server           Skip the 'MariaDB Server' repository.

    --skip-tools            Skip the 'Tools' repository.

    --skip-verify           Skip verification of MariaDB Server versions.
                            Use with caution as this can lead to an invalid
                            repository configuration file being created.

    --skip-check-installed  Skip tests for required prerequisites for this script.

    --skip-eol-check        Skip tests for versions being past their EOL date

    --skip-os-eol-check     Skip tests for operating system versions being past EOL date

    --write-to-stdout       Write output to stdout instead of to the OS's
                            repository configuration. This will also skip
                            importing GPG keys and updating the package 
                            cache on platforms where that behavior exists.
"

# os_type = ubuntu, debian, rhel, sles
os_type=
# os_version as demanded by the OS (codename, major release, etc.)
os_version=

# These GPG key IDs are used to fetch keys from a keyserver on Ubuntu & Debian
key_ids=( 0x8167EE24 0xE3C94F49 0xcbcb082a1bb943db 0xf1656f24c74cd1d8 0x135659e928c12247 )
# These GPG URLs are used to fetch GPG keys on RHEL and SLES
key_urls=(
    https://supplychain.mariadb.com/MariaDB-Server-GPG-KEY
    https://supplychain.mariadb.com/MariaDB-MaxScale-GPG-KEY
    https://supplychain.mariadb.com/MariaDB-Enterprise-GPG-KEY
)

msg(){
    type=$1 #${1^^}
    shift
    printf "# [$type] %s\n" "$@" >&2
}

error(){
    msg error "$@"
    exit 1
}

cap()
{
  printf '%s' "$1" | head -c 1 | tr [:lower:] [:upper:]
  printf '%s' "$1" | tail -c '+2'
}

verify_server_os_combo() {
  local failed=0
  local not_available="MariaDB Server ${mariadb_server_version_real} is not available for $(cap ${os_type}) $(cap ${os_version})"
  case $mariadb_server_version_real in
    *10.1[0-1]*) ;; # need to handle 10.10+
    *10.[0-4]*) case ${os_version} in jammy|bullseye) failed=1 ;; esac ;;
    *10.5*) case ${os_version} in jammy) failed=1 ;; esac ;;
  esac
  if (( $failed ))
  then
    # This verify_server_os_combo function only runs if MariaDB is not being
    # skipped. If Maxscale is being skipped then we return an error, otherwise
    # we just return a warning and skip configuring the Server repo.
    if ((skip_maxscale))
    then
      error "${not_available}"
    else
      msg warning "${not_available}, skipping..."
      skip_server=1
    fi
  fi
}

verify_mariadb_server_version() {
  # version regex
  if (($skip_eol_check)); then
    rx='^(mariadb-){0,1}(10\.[0-9]|10\.1[0-1]|10\.[0-9]\.[1-9]{0,1}[0-9]{1}|10\.1[0-1]\.[1-9]{1}[0-9]{0,1}|11\.[0-3]|11\.[0-3]\.[1-9]{1}[0-9]{0,1})$'
  else
    rx='^(mariadb-){0,1}(10\.[4569]|10\.1[0-1]|10\.[4569]\.[1-9]{0,1}[0-9]{1}|10\.1[0-1]\.[1-9]{1}[0-9]{0,1}|11\.[0-3]|11\.[0-3]\.[1-9]{1}[0-9]{0,1})$'
  fi
  if [[ $@ =~ $rx ]] ; then
    case $os_type in
      ubuntu|debian)
        verify_url="${url_mariadb_repo}/${mariadb_server_version_real}/repo/${os_type}/dists/${os_version}/Release"
        ;;
      rhel)
        verify_url="${url_mariadb_repo}/${mariadb_server_version_real}/yum/rhel/${os_version}/${arch}/repodata/repomd.xml"
        ;;
      sles)
        verify_url="${url_mariadb_repo}/${mariadb_server_version_real}/yum/sles/${os_version}/x86_64/repodata/repomd.xml"
        ;;
    esac
    error_log=$(mktemp)
    http_status_code=$(curl -LsS --stderr ${error_log} -o /dev/null -I -w "%{http_code}" ${verify_url})
    return_code="$?"
    error_output=$(cat ${error_log})
    rm -f ${error_log}

    case ${http_status_code} in
      200)
        msg info "MariaDB Server version ${mariadb_server_version_real} is valid"
        ;;
      403|404)
        get_version_info_server
        error "MariaDB Server version ${mariadb_server_version_real} is not working.
#         Please verify that the version is correct.
#         Not all releases of MariaDB are available on all distributions.
#${version_info}"
        ;;
      *)
        error_message="Problem encountered while trying to verify the MariaDB Server version:"
        if [[ "${return_code}" -gt "0" ]]; then
          get_version_info_server
          error "${error_message}
          $error_output ${version_info}"
        else
          get_version_info_server
          error "${error_message}
          Unexpected HTTP response code '${http_status_code}' ${version_info}"
        fi
        ;;
    esac
  else
    get_version_info_server
    error "MariaDB Server version ${mariadb_server_version_real} is not valid. ${version_info}"
  fi
}

get_version_info_server() {
  if [[ "${version_info}" = "" ]]; then
    latest_versions_server=$(curl -s https://dlm.mariadb.com/rest/releases/mariadb_server/)

    version_info="
#         The latest MariaDB Server versions are:
#             ${latest_versions_server}
#
#         More information on MariaDB releases is available at:
#             https://mariadb.com/kb/en/release-notes/"
  fi
}

version(){
    printf "mariadb_repo_setup %s\n" "$version"
}

while :; do
    case $1 in
        --version)
            version
            exit 0
            ;;
        --mariadb-server-version)
            if [[ -n $2 ]] && [[ $2 != --* ]]; then
                mariadb_server_version=$2
                shift
            else
                error "The $1 option requires an argument"
            fi
            ;;
        --mariadb-server-version=?*)
            mariadb_server_version=${1#*=}
            ;;
        --mariadb-server-version=)
            error "The $1 option requires an argument"
            ;;
        --mariadb-maxscale-version)
            if [[ -n $2 ]] && [[ $2 != --* ]]; then
                mariadb_maxscale_version=$2
                shift
            else
                error "The $1 option requires an argument"
            fi
            ;;
        --mariadb-maxscale-version=?*)
            mariadb_maxscale_version=${1#*=}
            ;;
        --mariadb-maxscale-version=)
            error "The $1 option requires an argument"
            ;;

        --write-to-stdout)
            write_to_stdout=1
            ;;

        --skip-key-import)
            skip_key_import=1
            ;;
        --skip-maxscale)
            skip_maxscale=1
            ;;
        --skip-server)
            skip_server=1
            ;;
        --skip-tools)
            skip_tools=1
            ;;
        --skip-verify)
            skip_verify=1
            ;;
        --skip-check-installed)
            skip_check_installed=1
            ;;
        --skip-eol-check)
	  skip_eol_check=1
	  ;;
        --skip-os-eol-check)
	  skip_os_eol_check=1
	  ;;

        --os-type)
            if [[ -n $2 ]] && [[ $2 != --* ]]; then
                os_type=$2
                shift
            else
                error "The $1 option requires an argument"
            fi
            ;;
        --os-type=?*)
            os_type=${1#*=}
            ;;
        --os-type=)
            error "The $1 option requires an argument"
            ;;
        --arch)
            if [[ -n $2 ]] && [[ $2 != --* ]]; then
                os_type=$2
                shift
            else
                error "The $1 option requires an argument"
            fi
            ;;
        --arch=?*)
            arch=${1#*=}
            # normalize arch names
            case $arch in
              amd64|x86_64)
                arch='x86_64'
                ;;
              aarch64|arm64)
                arch='aarch64'
                ;;
              *)
                error "You set arch=$arch but valid architectures are: x86_64 (amd64) and aarch64 (arm64)"
                ;;
            esac
            ;;
        --arch=)
            error "The $1 option requires an argument"
            ;;
        --os-version)
            if [[ -n $2 ]] && [[ $2 != --* ]]; then
                os_version=$2
                shift
            else
                error "The $1 option requires an argument"
            fi
            ;;
        --os-version=?*)
            os_version=${1#*=}
            ;;
        --os-version=)
            error "The $1 option requires an argument"
            ;;
        --help)
            version
            printf "%s" "$usage"
            exit
            ;;
        -?*)
            msg warning "Unknown option (ignored): $1\n"
            ;;
        *)
            break
    esac
    shift
done

# We accept setting os-type to centos or rocky, but we normalize it to 'rhel'
case ${os_type} in
  centos|rocky*) os_type='rhel' ;;
esac

open_outfile(){
    unset outfile
    if (( write_to_stdout ))
    then
        exec 4>&1
    else
        case $1 in
            ubuntu|debian) outfile=/etc/apt/sources.list.d/mariadb.list ;;
            rhel) outfile=/etc/yum.repos.d/mariadb.repo ;;
            sles) outfile=/etc/zypp/repos.d/mariadb.repo ;;
            *) error "Sorry, your OS is not supported." "$supported"
        esac
        if [[ -e $outfile ]]
        then
        local suffix=0
        while [[ -e $outfile.old_$((++suffix)) ]]; do :; done
            msg warning "Found existing file at $outfile. Moving to $outfile.old_$suffix"
        if ! mv "$outfile" "$outfile.old_$suffix"
            then
                error "Could not move existing '$outfile'. Aborting"\
                      "Use the --write-to-stdout option to see its effect without becoming root"
            fi
        fi
        if ! exec 4>"$outfile"
        then
            error "Could not open file $outfile for writing. Aborting"\
                  "Use the --write-to-stdout option to see its effect without becoming root"
        fi
    fi
}

identify_os(){
    if [[ ! $arch ]]
    then
    arch=$(uname -m)
    fi
    # Check for macOS
    if [[ $(uname -s) == Darwin ]]
    then
        printf '%s\n' \
            'To install MariaDB Server from a repository on macOS, please use Homebrew:' \
            '    https://mariadb.com/kb/en/mariadb/installing-mariadb-on-macos-using-homebrew/' \
            'Or use the native PKG installer:' \
            '    https://mariadb.com/kb/en/mariadb/installing-mariadb-server-pkg-packages-on-macos/'
        exit
    # Check for RHEL/CentOS, Fedora, etc.
    elif command -v rpm >/dev/null && [[ -e /etc/redhat-release ]]
    then
        os_type=rhel
        el_version=$(rpm -qa '(oraclelinux|sl|redhat|centos|fedora|rocky|alma)*release(|-server)' --queryformat '%{VERSION}')
        case $el_version in
            5*) os_version=5 ; ((skip_os_eol_check)) || error "RHEL/CentOS 5 is no longer supported" "$supported" ;;
            6*) os_version=6 ; ((skip_os_eol_check)) || error "RHEL/CentOS 6 is no longer supported" "$supported" ;;
            7*) os_version=7 ;;
            8*) os_version=8 ; extra_options="module_hotfixes = 1" ;;
            9*) os_version=9 ; extra_options="module_hotfixes = 1" ;;
             *) error "Detected RHEL or compatible but version ($el_version) is not supported." "$supported"  "$otherplatforms" ;;
         esac
    elif [[ -e /etc/os-release ]]
    then
        . /etc/os-release
        # Is it Debian?
        case $ID in
            debian)
                os_type=debian
                debian_version=$(< /etc/debian_version)
                case $debian_version in
                    9*) os_version=stretch ; ((skip_os_eol_check)) || error "Debian 9 'stretch' has reached End of Life and is no longer supported" "$supported" ;;
                    10*) os_version=buster ;;
                    11*) os_version=bullseye ;;
                    12*) os_version=bookworm ;;
                     *) error "Detected Debian but version ($debian_version) is not supported." "$supported"  "$otherplatforms" ;;
                esac
                ;;
            ubuntu)
                os_type=ubuntu
                . /etc/lsb-release
                os_version=$DISTRIB_CODENAME
                case $os_version in
                    precise ) ((skip_os_eol_check)) || error 'Ubuntu 12.04 LTS has reached End of Life and is no longer supported.' ;;
                    trusty  ) ((skip_os_eol_check)) || error 'Ubuntu 14.04 LTS has reached End of Life and is no longer supported.' ;;
                    xenial  ) ((skip_os_eol_check)) || error 'Ubuntu 16.04 LTS has reached End of Life and is no longer supported.' ;;
                    bionic  ) extra_options=" lang=none target-=CNF" ; url_base="archive.mariadb.org" ; url_mariadb_repo="https://${url_base}" ; mariadb_server_version_real="mariadb-${mariadb_server_version_num}" ;;
                    focal|jammy ) ;;
                    *) error "Detected Ubuntu but version ($os_version) is not supported." "Only Ubuntu LTS releases are supported."  "$otherplatforms" ;;
                esac
                if [[ $arch == aarch64 ]]
                then
                    case $os_version in
                        xenial ) ;;
                        bionic ) extra_options=" lang=none target-=CNF" ;;
                        focal|jammy ) ;;
                        *) error "Only 18.04/bionic, 20.04/focal, & 22.04/jammy are supported for ARM64. Detected version: '$os_version'" ;;
                    esac
                fi
                ;;
            sles)
                os_type=sles
                os_version=${VERSION_ID%%.*}
                case $os_version in
                  12|15) ;;
                  *) error "Detected SLES but version ($os_version) is not supported."  "$otherplatforms" ;;
                esac
                ;;
        esac
    fi
    if ! [[ $os_type ]] || ! [[ $os_version ]]
    then
        error "Could not identify OS type or version." "$supported"
    fi
}

check_installed() {
  local not_installed
  local number_not_installed
  local install_message
  local need_to_install
  not_installed=""
  need_to_install=false
  for package in "$@" ; do
    case ${os_type} in
      debian|ubuntu)
        if { dpkg -l "${package}" | grep ii; } &>/dev/null ; then
          need_to_install=false
        else
          need_to_install=true
        fi
        ;;
      rhel)
        if { yum list installed "${package}" ; } &>/dev/null ; then
          need_to_install=false
        else
          need_to_install=true
        fi
        ;;
      sles)
        if { rpm -q "${package}" ; } &>/dev/null ; then
          need_to_install=false
        else
          need_to_install=true
        fi
        ;;
    esac
    if ${need_to_install} ; then
      if [ "${not_installed}" = "" ] ; then
        # number of not installed packages is 1
        not_installed="${package}"
        number_not_installed=1
      else
        # number of not installed packages is >1
        not_installed="${not_installed} ${package}"
        number_not_installed=2
      fi
    fi
  done
  if [ "${not_installed}" != "" ] ; then
      # One or more packages are not installed
      case ${number_not_installed} in
        1) install_message="The following package is needed by the script, but not installed:" ;;
        2) install_message="The following packages are needed by the script, but not installed:" ;;
      esac

      error "${install_message}
            ${not_installed}
        Please install and rerun the script.
        To disable this check add the \`--skip-check-installed\` flag"
  fi
}

remove_mdbe_repo(){
    case $os_type in
        debian|ubuntu)
            # First, remove the MariaDB Enterprise Repository config package, if it's installed
            if dpkg -l mariadb-enterprise-repository &>/dev/null
            then
                msg info 'Removing mariadb-enterprise-repository package...'
                dpkg -P mariadb-enterprise-repository
            fi
            ;;
        rhel|sles)
            # First, remove the MariaDB Enterprise Repository config package, if it's installed
            if rpm -qs mariadb-enterprise-repository &>/dev/null
            then
                msg info 'Removing mariadb-enterprise-repository package...'
                rpm -e mariadb-enterprise-repository
            fi
            ;;
    esac
}

clean_package_cache(){
  msg info 'Cleaning package cache...'
  case $1 in
    yum)
      yum clean all
      ;;
    dnf)
      dnf clean all
      ;;
    zypper)
      zypper clean --all
      ;;
  esac
}

# The directory structure of the MariaDB Server repo is such that the directories for each
# version have "mariadb-" prepended to the version number (i.e. mariadb-10.1 instead of 10.1)
# for 10.6 this has changed to just the version number
if [[ $mariadb_server_version = mariadb-* ]]
then
    mariadb_server_version_num=${mariadb_server_version#*-}
else
    mariadb_server_version_num=$mariadb_server_version
    mariadb_server_version=mariadb-$mariadb_server_version
fi

mariadb_server_version_real=$mariadb_server_version_num

# If we're writing the repository info to stdout, let's not try to import the signing keys.
((write_to_stdout)) && skip_key_import=1

if [[ ! $arch ]]
then
  arch=$(uname -m)
  case $arch in
    amd64|x86_64)
      arch='x86_64'
      ;;
    aarch64|arm64)
      arch='aarch64'
      ;;
  esac
fi

case $arch in
    x86_64) ;;
    aarch64) skip_tools=1;;
    *) error "The MariaDB Repository only supports x86_64 and aarch64 (detected $arch)." "$supported" "$otherplatforms" ;;
esac

if [[ $os_type ]] && [[ $os_version ]]
then
    # Both were given on the command line, so we'll just try using those.
    msg info "Skipping OS detection and using OS type '$os_type' and version '$os_version' as given on the command line"
    # We're skipping OS detection, so set extra_options to the correct value
    # for RHEL
    case $os_version in
      7*|8*|9*)
        if [ $os_type = 'rhel' ] ; then
          case $os_version in
            7*) os_version=7 ;;
            8*) os_version=8 ; extra_options="module_hotfixes = 1" ;;
            9*) os_version=9 ; extra_options="module_hotfixes = 1" ;;
          esac
        elif [ $os_type = 'debian' ] ; then
          case $os_version in
            7) os_version='wheezy' ; ((skip_os_eol_check)) || msg warning "Debian 7 'wheezy' has reached End of Life and is no longer supported." "$supported" ;;
            8) os_version='jessie' ; ((skip_os_eol_check)) || msg warning "Debian 8 'jessie' has reached End of Life and is no longer supported." "$supported" ;;
            9) os_version='stretch' ; ((skip_os_eol_check)) || msg warning "Debian 9 'stretch' has reached End of Life and is no longer supported" "$supported" ;;
          esac
        else
          error "--os-version='$os_version' is only valid if --os-type='rhel', you gave '$os_type'" "$supported"
        fi
        ;;
      10|11)
        if [ $os_type = 'debian' ] ; then
          case $os_version in
            10) os_version='buster' ;;
            11) os_version='bullseye' ;;
          esac
        else
          error "--os-version='$os_version' is only valid if --os-type='debian', you gave '$os_type'" "$supported"
        fi
        ;;
      12*)
        if [ $os_type = 'sles' ] ; then
          case $os_version in
            12*) os_version=12 ;;
          esac
        elif [ $os_type = 'debian' ] ; then
          case $os_version in
            12*) os_version='bookworm' ;;
          esac
        else
          error "--os-version='$os_version' is only valid if --os-type='sles' or 'debian', you gave '$os_type'" "$supported"
        fi
        ;;
      15*)
        if [ $os_type = 'sles' ] ; then
          case $os_version in
            15*) os_version=15 ;;
          esac
        else
          error "--os-version='$os_version' is only valid if --os-type='sles', you gave '$os_type'" "$supported"
        fi
        ;;
      xenial|bionic|focal|jammy)
        if [ $os_type != 'ubuntu' ] ; then
          error "--os-version='$os_version' is only valid if --os-type='ubuntu', you gave '$os_type'" "$supported"
        fi
        ;;
      stretch|buster|bullseye|bookworm)
        if [ $os_type != 'debian' ] ; then
          error "--os-version='$os_version' is only valid if --os-type='debian', you gave '$os_type'" "$supported"
        fi
        ;;
      *) error "--os-type='$os_type' with --os-version='$os_version' is an invalid combination" "$supported" ;;
    esac
elif [[ $os_type ]] || [[ $os_version ]]
then
    error 'If you give either --os-type or --os-version, you must give both.'
else
    identify_os
fi

# Handle various aarch64 repositories
if [[ "$arch" = 'aarch64' ]] ; then
  case $os_version in
    7)
      ((skip_maxscale)) || msg info "Skipping MariaDB MaxScale as RHEL 7 does not have aarch64 packages available."
      ((skip_maxscale)) || skip_maxscale=1
      ;;
    12)
      if [ $os_type = 'sles' ] ; then
      error "There are no aarch64 packages available for MariaDB Server or MariaDB MaxScale for SLES 12."
      fi
      ;;
    15)
      ((skip_server)) || msg warning "Skipping MariaDB Server as there are no aarch64 packages available."
      ((skip_server)) || skip_server=1
      ;;
  esac
fi

if (($skip_check_installed))
then
  msg info "Skipping check for script prerequisites."
else
  msg info "Checking for script prerequisites."
case $os_version in
  stretch) check_installed curl ca-certificates apt-transport-https ;;
  *) check_installed curl ca-certificates ;;
esac
fi

# To support old versions for testing purposes which are not on dlm.mariadb.com
case ${mariadb_server_version} in
    *10.1[0-9]*) ;; # everything >= 10.10 is on the new dlm for sure
    *10.0*) ;& # 10.0 releases are on the old download server only
    *10.1*) ;& # same for 10.1
    *10.2*) ;& # same for 10.2
    *10.3.[0-2]*|*10.3.[0-9]) ;& # 10.3: old server has <= .32, dlm has >= .29, we switch at .30
    *10.4.[0-1]*|*10.4.[0-9]) ;& # 10.4: dlm has >= 10.4.20
    *10.5.[0-9])     # 10.5: dlm has >= 10.5.10
    url_base="downloads.mariadb.com"
    url_mariadb_repo="https://${url_base}/MariaDB"
    mariadb_server_version_real=$mariadb_server_version
    ;;
esac

rhel_repo_server="
[mariadb-main]
name = MariaDB Server
baseurl = ${url_mariadb_repo}/%s/yum/rhel/%s/%s
gpgkey = file:///etc/pki/rpm-gpg/MariaDB-Server-GPG-KEY
gpgcheck = 1
enabled = 1
%s"
rhel_repo_maxscale='
[mariadb-maxscale]
# To use the latest stable release of MaxScale, use "latest" as the version
# To use the latest beta (or stable if no current beta) release of MaxScale, use "beta" as the version
name = MariaDB MaxScale
baseurl = https://dlm.mariadb.com/repo/maxscale/%s/yum/rhel/%s/%s
gpgkey = file:///etc/pki/rpm-gpg/MariaDB-MaxScale-GPG-KEY
gpgcheck = 1
enabled = 1'
rhel_repo_tools='
[mariadb-tools]
name = MariaDB Tools
baseurl = https://downloads.mariadb.com/Tools/rhel/%s/x86_64
gpgkey = file:///etc/pki/rpm-gpg/MariaDB-Enterprise-GPG-KEY
gpgcheck = 1
enabled = 1'

deb_repo_server="
# MariaDB Server
# To use a different major version of the server, or to pin to a specific minor version, change URI below.
deb [arch=amd64,arm64] ${url_mariadb_repo}/%s/repo/%s %s main"
deb_repo_server_debug="deb [arch=amd64,arm64${extra_options}] ${url_mariadb_repo}/%s/repo/%s %s main/debug"
deb_repo_maxscale='
# MariaDB MaxScale
# To use the latest stable release of MaxScale, use "latest" as the version
# To use the latest beta (or stable if no current beta) release of MaxScale, use "beta" as the version
deb [arch=amd64,arm64] https://dlm.mariadb.com/repo/maxscale/%s/%s %s main'
deb_repo_tools='
# MariaDB Tools
deb [arch=amd64] http://downloads.mariadb.com/Tools/%s %s main'

sles_repo_server="
[mariadb-server]
name = MariaDB Server
baseurl = ${url_mariadb_repo}/%s/yum/sles/%s/x86_64
gpgkey = file:///etc/pki/trust/MariaDB-Server-GPG-KEY
gpgcheck = 1
type=rpm-md
enabled = 1
autorefresh=1
priority=10"
sles_repo_maxscale='
[mariadb-maxscale]
# To use the latest stable release of MaxScale, use "latest" as the version
# To use the latest beta (or stable if no current beta) release of MaxScale, use "beta" as the version
name = MariaDB MaxScale
baseurl = https://dlm.mariadb.com/repo/maxscale/%s/yum/sles/%s/%s
gpgkey = file:///etc/pki/trust/MariaDB-MaxScale-GPG-KEY
enabled = 1
autorefresh=1
gpgcheck = 1
type=rpm-md
priority=10'
sles_repo_tools='
[mariadb-tools]
name = MariaDB Tools
baseurl = https://downloads.mariadb.com/Tools/sles/%s/x86_64
gpgkey = file:///etc/pki/trust/MariaDB-Enterprise-GPG-KEY
enabled = 1
autorefresh=1
gpgcheck = 1
type=rpm-md
priority=10'

open_outfile "$os_type"

# If we're not writing to stdout, try to remove the mariadb-enterprise-repository package
((write_to_stdout)) || remove_mdbe_repo


# Before we get into creating the configuration file, check the combination of
# MariaDB version and OS
((skip_server)) || verify_server_os_combo

case $os_type in
    ubuntu|debian)
        # should be a valid version, so verify it is so
        ((skip_server)) || ((skip_verify)) || verify_mariadb_server_version $mariadb_server_version_real
        # If we are not writing to stdout, create an apt preferences file to give our 
        # packages the highest possible priority
        if ((write_to_stdout))
        then
            msg info 'If run without --write-to-stdout, this script will create /etc/apt/preferences.d/mariadb-enterprise.pref to give packages from MariaDB repositories highest priority, in order to avoid conflicts with packages from OS and other repositories.'
        else
            printf '%s\n' \
            'Package: *' \
            "Pin: origin ${url_base}" \
            'Pin-Priority: 1000' \
            > /etc/apt/preferences.d/mariadb-enterprise.pref
        fi
        { 
            ((skip_server)) || printf "$deb_repo_server\n\n" "$mariadb_server_version_real" "$os_type" "$os_version"
            case $os_type in
              ubuntu)
                ((skip_server)) || printf "$deb_repo_server_debug\n\n" "$mariadb_server_version_real" "$os_type" "$os_version"
                ;;
            esac
            ((skip_maxscale)) || printf "$deb_repo_maxscale\n\n" "$mariadb_maxscale_version" "apt" "$os_version"
            ((skip_tools)) || printf "$deb_repo_tools\n" "$os_type" "$os_version"
        } >&4
        ((write_to_stdout)) || msg info "Repository file successfully written to $outfile"
        if ! ((skip_key_import))
        then
            msg info 'Adding trusted package signing keys...' 
            if curl -LsSO https://supplychain.mariadb.com/mariadb-keyring-2019.gpg
            then
                if curl -LsS https://supplychain.mariadb.com/mariadb-keyring-2019.gpg.sha256 | sha256sum -c --quiet
                then
                    msg info 'Running apt-get update...'
                    if mv mariadb-keyring-2019.gpg /etc/apt/trusted.gpg.d/ &&
                      chmod 644 /etc/apt/trusted.gpg.d/mariadb-keyring-2019.gpg &&
                      apt-get -qq update
                    then
                        msg info 'Done adding trusted package signing keys'
                    else
                        msg error 'Failed to add trusted package signing keys'
                    fi
                else
                    msg error 'Failed to verify trusted package signing keys keyring file'
                fi
            else
                msg error 'Failed to download trusted package signing keys keyring file'
            fi
        elif ((write_to_stdout))
        then
            msg info 'If run without --skip-key-import/--write-to-stdout, this script will import package signing keys used by MariaDB'
        fi
        ;;
    rhel)
        ((skip_server)) || ((skip_verify)) || verify_mariadb_server_version $mariadb_server_version_real
        {
            ((skip_server)) || printf "$rhel_repo_server\n\n" "$mariadb_server_version_real" "$os_version" "$arch" "$extra_options"
            ((skip_maxscale)) || printf "$rhel_repo_maxscale\n\n" "$mariadb_maxscale_version" "$os_version" "$arch"
            ((skip_tools)) || printf "$rhel_repo_tools\n" "$os_version"
        } >&4
        ((write_to_stdout)) || msg info "Repository file successfully written to $outfile"
        if ! ((skip_key_import))
        then
            msg info 'Adding trusted package signing keys...'
            if rpm --import "${key_urls[@]}"
            then
                pushd /etc/pki/rpm-gpg/
                  for key in ${key_urls[@]} ; do curl -LsSO ${key};done
                popd
                msg info 'Successfully added trusted package signing keys'
            else
                msg error 'Failed to add trusted package signing keys'
            fi
        fi
        ((write_to_stdout)) || clean_package_cache yum
        ;;
    sles)
        ((skip_server)) || ((skip_verify)) || verify_mariadb_server_version $mariadb_server_version_real
        {
            ((skip_server)) || printf "$sles_repo_server\n\n" "$mariadb_server_version_real" "$os_version"
            ((skip_maxscale)) || printf "$sles_repo_maxscale\n\n" "$mariadb_maxscale_version" "$os_version" "$arch"
            ((skip_tools)) || printf "$sles_repo_tools\n" "$os_version"
        } >&4
        ((write_to_stdout)) || msg info "Repository file successfully written to $outfile"
        if ! ((skip_key_import))
        then
            if [[ $os_version = 11 ]]
            then
                # RPM in SLES 11 doesn't support HTTPS, so munge the URLs to use standard HTTP
                rpm --import "${key_urls[@]/#https/http}"
            else
                msg info 'Adding trusted package signing keys...'
                if rpm --import "${key_urls[@]}"
                then
                    pushd /etc/pki/trust/
                      for key in ${key_urls[@]} ; do curl -LsSO ${key};done
                    popd
                    msg info 'Successfully added trusted package signing keys'
                else
                    msg error 'Failed to add trusted package signing keys'
                fi
            fi
        fi
        ((write_to_stdout)) || clean_package_cache zypper
        ;;
    *)
        error "Sorry, your OS is not supported." "$supported"
        ;;
esac
