#!/bin/bash
#
# automated RGM installer
#
# call this script remotely with the following one-liner:
#   bash <(curl -s https://installer.rgm-cloud.io/rgm-installer.sh) <client cert name>
#
# This will do the following:
# - install RGM prerequisites packages (openssl, EPEL, ansible)
# - install on host the registered RGM instance certificate delivered by RGM's PKI
# - configure RGM's package repository
# - clone RGM Ansible stuff
# - automatically partition and format unused drives for RGM usage
# - automatically install RGM
# - installs & configure OpenVPN if NOC subscription
#
# Initial write by Eric Belhomme <ebelhomme@fr.scc.com>
# contributions from Mickaël Aubertin <maubertin@fr.scc.com>
#   - initial auto-partionner code
# contributions from Vincent Fricou <vincent@fricouv.eu>
#   - initial hardware check requirements
#
# Copyright by SCC France SA (2019 onwards), released under the terms of the GNU General License version 2


RC=1
if [ $UID -ne 0 ]; then
    echo -e "\e[1;31mError :\e[22m the RGM installer requires root privileges to execute\e[0m"
    exit 1
fi

LANG=C
# General RGM constants for RPM and Git repositories
RGM_WEBSITE="https://www.rgm-cloud.io/"
RGM_INSTALLER_URI="https://installer.rgm-cloud.io/"
RGM_ANSIBLE_REPO="https://github.com/RGM-OSC/ansible-playbook-rgm-installer.git"
#ANSIBLE_RGM_DIR=$(basename "$RGM_ANSIBLE_REPO" | sed 's/\.git//')
ANSIBLE_RGM_DIR="${HOME}/rgm-installer"
ANSIBLE_ROLE_REQS='requirements.yml'
ENABLE_BUSINESS=0

ELRELEASE="$(sed -E 's/^.* ([0-9]+)\.[0-9\.]+ .*/\1/' /etc/redhat-release)"

GIT_BRANCH_MASTER="master"
GIT_BRANCH_RAWHIDE="rawhide/el${ELRELEASE}"

if [ "${ELRELEASE}" -gt "7" ]; then
    PKG='dnf'
    PKGCONFIG='/etc/dnf/dnf.conf'
else
    PKG='yum'
    PKGCONFIG='/etc/yum.conf'
fi

# The following arrays describes the mountpoints to create with their respective parameters:
# AR_PART_INC: can we append this mountpoint the the list (0 or 1)?
# AR_PART_NAM: LVM LV name
# AR_PART_MNT: target mountpoint
# AR_PART_FST: filesystem to use
# AR_PART_SIZ: minimum required volume size
# AR_PART_PER: percentage of the remaining extra storage space to assign to this mountpoint
#
# Note: the arrays are tabbed only to ease reading the script...
AR_PART_INC=( 1          0                        0                 0                   0 )
AR_PART_NAM=( "rgm"      "elastic"                "backup"          "influxdb"          "mariadb")
AR_PART_MNT=( "/srv/rgm" "/var/lib/elasticsearch" "/srv/rgm/backup" "/var/lib/influxdb" "/var/lib/mysql")
AR_PART_FST=( "ext4"     "xfs"                    "ext4"            "xfs"               "xfs"   )
AR_PART_SIZ=( 5          20                       20                10                  5 )
AR_PART_PER=( 5          30                       30                20                  0 )

# CPU cores requirements
HARD_REQ_CPU=4
# Memory requirements (in GB)
HARD_REQ_MEM=16

COMMERCIALS_LIST=( \
    'oracle' \
    'vmware' \
    'java'
)

# internal variables default values
# reminder: in bash 0 is true, >=1 is false
ASSUMEYES=1
VARSREVIEW=0
NOHWREQ=0
NOANSIBLE=1
AUTOPART=0
CLONEDEV=1
RGMP12=
PROXY=
PROXY_HOST=
PROXY_PORT=
EXTRAVARS=()
RGMPWD=
COMMERCIALS=
SKIPTAGS='--skip-tags business'

LOGFILE="$(pwd -P)/rgm-installer_1liner.$(date +%Y%m%d).log"
if [ ! -e "$LOGFILE" ]; then
    touch "$LOGFILE"
    echo '' >> "$LOGFILE"
    echo "*** RGM one-liner started on $(date) ***" >> "$LOGFILE"
fi


function pkg_config_manager {
    # $1 enable/disable
    # $2 repo name
    local cmd
    cmd=''
    if [[ "${1}" =~ ^enable.* ]]; then
    test ${ELRELEASE} -gt 7 && cmd='dnf config-manager --set-enabled'
    test ${ELRELEASE} -le 7 && cmd='yum-config-manager --enable'
    else
    test ${ELRELEASE} -gt 7 && cmd='dnf config-manager --set-disabled'
    test ${ELRELEASE} -le 7 && cmd='yum-config-manager --disable'
    fi
    ${cmd} "$2"
}


function rgm_log {
    echo "$1" >> "$LOGFILE"
}


function add_or_upate {
    SEARCH_PATTERN="$1"
    LINE_TO_ADD="$2"
    FILENAME="$3"

    STR=$(grep -Poh "$SEARCH_PATTERN" "$FILENAME")
    if [ -n "$STR" ]; then
        sed -i "s|${STR}|${LINE_TO_ADD}|" "$FILENAME"
    else
        echo "${LINE_TO_ADD}" >> "$FILENAME"
    fi
}


# NOHWREQ possible values
# 0 normal hardware test
# 1 soft disable of hw reqs (memory limit to 4GB)
# 2 hard disable memory requirement
function check_hardware_requirements {
    local MEM_TOTAL CPU_COUNT HARD_REQ_LOW HARD_REQ_MEM_ORIG
    CPU_COUNT=0
    # bit 1 : low CPU
    # bit 2 : low memory
    HARD_REQ_LOW=0
    HARD_REQ_MEM_ORIG="$HARD_REQ_MEM"
    MEM_TOTAL=$(( $(grep 'MemTotal' /proc/meminfo | awk '{print $2}') / 1024 / 1024 + 1 ))
    CPU_COUNT=$(( $(lscpu | grep 'Core(s) per socket' | cut -d: -f2 | xargs) * $(lscpu | grep 'Socket(s)' | cut -d: -f2 | xargs) ))

    if [ ${CPU_COUNT} -lt ${HARD_REQ_CPU} ] && [ $NOHWREQ -le 1 ]; then
        echo -e " \n \e[41;97;1mYour system doesn't meet CPU cores requirements.\e[0m"
        echo -e "\e[93mMinimum CPU required ${HARD_REQ_CPU}.\e[0m"
        HARD_REQ_LOW=$(( HARD_REQ_LOW +1 ))
    fi
    if [ $NOHWREQ -gt 0 ]; then
        HARD_REQ_MEM=4
        echo -e "\e[93mmemory check dropped to ${HARD_REQ_MEM} GB by user request.\e[0m Normal memory requirement is ${HARD_REQ_MEM_ORIG} GB..."
    fi
    if [ ${MEM_TOTAL} -lt ${HARD_REQ_MEM} ]; then

        echo -e " \n \e[41;97;1mYour system doesn't meet memory requirements.\e[0m"
        echo -e "\e[93mMinimum memory required ${HARD_REQ_MEM}GB.\e[0m"
        HARD_REQ_LOW=$(( HARD_REQ_LOW +2 ))
    fi
    if [ ${HARD_REQ_LOW} -gt 0 ]; then
        if [ $HARD_REQ_MEM -lt $HARD_REQ_MEM_ORIG ] && [ $((HARD_REQ_LOW >> 1)) -eq 1 ]; then
            # This is the very minimum, systems with less than 2GB simply won't start...
            echo -e "\e[93mRGM can't run with less than 2GB (recomanded ${HARD_REQ_MEM}GB).\e[0m"
            echo -e "Please upgrade memory to  ${HARD_REQ_MEM}GB or more...\n"
            rgm_log "EXIT FAIL: hadware requirements not met"
            exit 1
        fi
        if [ $NOHWREQ -lt 1 ]; then
            echo -e "\nTo bypass hardware checks, use \e[1m-b\e[0m flag."
            rgm_log "EXIT FAIL: hadware requirements not met"
            exit 1
        else
            echo -e "\e[93mHardware checks bypassed by user request.\e[0m"
        fi
    fi
}


function ask_yesno {
    if [ -n "$1" ]; then
        echo -e "$1"
    fi
    read -r YESNO
    if [[ $YESNO =~ [yY] ]]; then
        return 0
    fi
    return 1
}


function print_help {

    echo -e "\n \e[1m-+- Online \e[34mRGM\e[39m installer - $RGM_WEBSITE -+-\e[0m\n"
    cat <<EOF
parameters:
  -h                         : this help
  -y                         : assume yes
  -b                         : disable minimum hardware checks requirements:
                               -b: soft disable of hardware requirements
                               -bb: hard disable of memory requirement (use at your own risk)
  -v                         : disable Ansible 'vars' file review (enabled by default)
  -u                         : disable auto-partition of unpartitioned disk space (enabled by default)
  -d                         : clone 'dev' branch instead of ${GIT_BRANCH_MASTER} stable version
  -n                         : don't execute ansible playbook
  -e <extra vars>            : execute RGM Ansible playbook with provided extra_vars
  -p <proxy_host:proxy_port> : specify a HTTP proxy
  -c <pkcs#12 filename>      : RGM PKCS#12 subscription file for registered Business customer
  -o oracle | vmware | java  : allow installation of commercial software (implies user acceptance of respective licenses)
EOF
#  -4 <4any central host>     : register RGM instance to 4any central monitoring
    exit 2
}


function add_extra_var {
    EXTRAVARS+=(--extra-vars "$1")
}


function check_commercial {
    if [[ " ${COMMERCIALS_LIST[*]} " =~ [[:space:]]${1}[[:space:]] ]]; then
        COMMERCIALS+=("$1")
    else
        echo "Error: '-o $1' is not an acceptable argument. Allowed -o flags are '${COMMERCIALS_LIST[*]}'"
        exit 1
    fi
}


function check_yaml_customized {
    STARTLINE=$(grep -n '^### Begining.*rgm-installer.sh one-liner script$' "${ANSIBLE_RGM_DIR}/host_vars/localhost/localhost.yml" | cut -d ':' -f 1 | head -n1)
    ENDLINE=$(grep -n '^### End of.*rgm-installer.sh one-liner script$' "${ANSIBLE_RGM_DIR}/host_vars/localhost/localhost.yml" | cut -d ':' -f 1 | tail -n1)
    if [[ -z "$STARTLINE" || -z "$ENDLINE" ]]; then
        return 0
    fi
    if [ $(( ENDLINE - STARTLINE )) -gt 1 ]; then
        return 1
    else
        sed -i '/^### .*rgm-installer.sh one-liner script$/d' "${ANSIBLE_RGM_DIR}/host_vars/localhost/localhost.yml"
        return 0
    fi
}


function generate_disk_partition {

    if ! check_yaml_customized; then
        echo "auto-partitioning skipped because yaml file already contain partition information"
        return
    fi
    mapfile -t SYSDISKS < <(lsblk -lo NAME,MAJ:MIN,TYPE | grep 'disk$' | awk '{print $1}')

    USEDDISKS=()
    for item in $(lsblk -a -i | grep part | awk '{print $1}' | cut -d '-' -f 2); do
        for dsk in "${SYSDISKS[@]}"; do
            if echo "$item" | grep "$dsk" &> /dev/null; then
                if ! echo "${USEDDISKS[@]}" | grep "$dsk" &> /dev/null; then
                    USEDDISKS=("${USEDDISKS[@]}" "$dsk")
                fi
            fi
        done
    done
    AVAILDISKS=()
    for item in "${SYSDISKS[@]}"; do
        if ! echo "${USEDDISKS[@]}" | grep "$item" &> /dev/null; then
            AVAILDISKS=("${AVAILDISKS[@]}" "$item")
        fi
    done
    if [ ${#AVAILDISKS[@]} -eq 0 ]; then
        return
    fi

    MaxSize=0
    BiggestDisk=""
    for Disk in "${AVAILDISKS[@]}"; do
        DiskSize="$(lsblk "/dev/$Disk" -b -n -d --output SIZE)"
        if [ "$DiskSize" -gt $MaxSize ]; then
            MaxSize=$DiskSize
            BiggestDisk=$Disk
        fi
    done

    TotalPercent=0
    for idx in ${!AR_PART_PER[*]}; do
        TotalPercent=$(( TotalPercent + ${AR_PART_PER[$idx]} ))
    done
    if [ $TotalPercent -gt 100 ]; then
        echo -e " \n \e[41;97;1mError: sum of AR_PART_PER can't be greater than 100% !\e[0m"
        echo -e " Please fill a bug report on \e[1;34mRGM\e[0m website:\n \e[1m$RGM_WEBSITE\e[0m\n"
        rgm_log "EXIT FAIL: auto-partitionning returned $TotalPercent % disk allocation"
        exit 1
    fi

    # check if min size reqs are valiated
    SizCum=0
    for idx in ${!AR_PART_MNT[*]}; do
        CurSize=$(( SizCum + (${AR_PART_SIZ[$idx]} * 1024 * 1024 * 1024) ))
        if [ $CurSize -lt "$MaxSize" ]; then
            AR_PART_INC[$idx]=1
            SizCum=$CurSize
        fi
    done
    # if disk space if bigger than min reqs, then divide and allocate the remaining as specified by $AR_PART_PER
    ExtraStorageToSplit=$(( MaxSize - SizCum ))
    if [[ ! ${AR_PART_INC[*]} =~ 0 && $ExtraStorageToSplit -gt $(( 1024 * 1024 * 1024 )) ]]; then
        for idx in ${!AR_PART_MNT[*]}; do
            if [ ${AR_PART_INC[$idx]} -eq 1 ]; then
                AR_PART_SIZ[$idx]=$(( ((${AR_PART_SIZ[$idx]} * 1024 * 1024 * 1024) + (ExtraStorageToSplit/100) * ${AR_PART_PER[$idx]}) / 1024 / 1024 / 1024 ))
            fi
        done
    fi
    # write YAML file header
    cat > "${HOME}/rgm-installer_auto-partition.yml" <<EOF

### Begining of variables appended automatically by rgm-installer.sh one-liner script
lvm_disk:
  device: '/dev/${BiggestDisk}'
  lvm_vg: 'vg_rgmdata'
  partitions:
EOF
    rgm_log "LVM config: found a LVM PV [/dev/${BiggestDisk}], created VG [vg_rgmdata]"
    # write YAML partitions
    for idx in ${!AR_PART_MNT[*]}; do
        if [ ${AR_PART_INC[$idx]} -eq 1 ]; then
            cat >> "${HOME}/rgm-installer_auto-partition.yml" <<EOF
  - name: '${AR_PART_NAM[$idx]}'
    mountpoint: '${AR_PART_MNT[$idx]}'
    filesystem: '${AR_PART_FST[$idx]}'
    size: '${AR_PART_SIZ[$idx]}G'
EOF
            rgm_log "LVM config: created LV ${AR_PART_NAM[$idx]} (${AR_PART_SIZ[$idx]}GB), moutpoint at '${AR_PART_MNT[$idx]}', formatted with ${AR_PART_FST[$idx]} filesystem"
        fi
    done
    echo -e "### End of variables appended automatically by rgm-installer.sh one-liner script\n" >> "${HOME}/rgm-installer_auto-partition.yml"
    cat "${HOME}/rgm-installer_auto-partition.yml" >> "${ANSIBLE_RGM_DIR}/host_vars/localhost/localhost.yml"
}


while getopts hynubvc:p:de:o: arg; do
    case "$arg" in
        h) print_help;;
        y) ASSUMEYES=0
            rgm_log "ARGS: 'assume yes' requested"
            ;;
        n) NOANSIBLE=0
            rgm_log "ARGS: no ansible execution requested"
            ;;
        u) AUTOPART=1
            rgm_log "ARGS: no LVM auto-partitionning requested"
            ;;
        v) VARSREVIEW=1
            rgm_log "ARGS: no ansible vars review requested"
            ;;
        b) NOHWREQ=$(( NOHWREQ +1 ))
            rgm_log "ARGS: no hardware check requested $NOHWREQ"
            ;;
        c) RGMP12="$OPTARG"
            rgm_log "ARGS: PKCS12 RGM customer certitificate provided: [$RGMP12]"
            ;;
        p) PROXY="$OPTARG"
            rgm_log "ARGS: proxy server provided: [$PROXY]"
            ;;
        d) CLONEDEV=0
            rgm_log "ARGS: Request to clone Ansible dev branches instead of ${GIT_BRANCH_MASTER} (stable)"
            ;;
        e)
            for ITEM in $OPTARG; do
                add_extra_var "$ITEM"
                rgm_log "ARGS: Provided Ansible extra_vars: [$ITEM]"
            done
            ;;
        o)
            check_commercial "$OPTARG"
            while [ "$OPTIND" -le "$#" ] && [ "${!OPTIND:0:1}" != "-" ]; do
                check_commercial "${!OPTIND}"
                OPTIND=$(( OPTIND + 1 ))
            done
            ;;
        *) print_help;;
  esac
done

echo -e "\n\e[1m -+- Welcome to online \e[34mRGM\e[39m installer - $RGM_WEBSITE -+-\e[0m\n"
check_hardware_requirements

if [ -n "$PROXY" ]; then
    if ! echo "$PROXY" | grep -P '^[\w\._-]+:\d{2,5}$' &> /dev/null; then
        echo "Error: supplied proxy arg does *not* fill with requirement"
        echo "Expected format is '<host/ip>:<port>'"
        exit 1
    fi
    PROXY_HOST=$(echo "$PROXY" | cut -d ':' -f 1)
    PROXY_PORT=$(echo "$PROXY" | cut -d ':' -f 2)
fi

if [ -z "$RGMP12" ]; then

    echo -e " \e[41;97;1m /!\\ Notice: No PKCS12 client certificate provided /!\\ \e[0m\n"
    echo -e "\e[1;34mRGM\e[0m installation will failback to \e[93mCommunity Edition\e[0m\n"
    echo -e "If you require \e[1mRGM registered installation\e[0m, please contact your \e[1;34mSCC\e[0m sales person\nto ask for a \e[1mRGM subscription\e[0m\n"

    if [ $ASSUMEYES  -eq 1 ]; then
        if ! ask_yesno "Proceed with \e[93mCommunity\e[0m installation ? (y/\e[1mN\e[0m)"; then
            echo "RGM installation aborted by user request"
            rgm_log "EXIT FAIL: user abort"
            exit 1
        fi
    fi
else
#    echo -e "This will install \e[34mRGM\e[39m with \e[1msubscription\e[0m for \e[92m$RGMP12\e[0m\n"
    echo -e "This will install \e[34mRGM\e[39m \e[1mBusiness Edition\e[0m\n"
fi

# configure yum proxy if requested
if [ -n "$PROXY" ]; then
    add_or_upate '^(#\s*)?proxy=.*$' "proxy=http://${PROXY_HOST}:${PROXY_PORT}" $PKGCONFIG
    rgm_log "YUM: configure an HTTP proxy: http://${PROXY_HOST}:${PROXY_PORT}"-
fi

### install prerequisites

# updating ca-certificates makes yum more reliable when dealing with metalinks
echo "update ca-certificates package"
$PKG --disablerepo=epel -y update ca-certificates &>> "$LOGFILE"

# install epel-release,rgm-release, scc-release
$PKG install -y epel-release \
    https://rpms.scc-services.fr/stable/el${ELRELEASE}/x86_64/Packages/scc-release-${ELRELEASE}-0.el${ELRELEASE}.noarch.rpm \
    https://rpms.scc-services.fr/stable/el${ELRELEASE}/x86_64/Packages/rgm-release-${ELRELEASE}-0.el${ELRELEASE}.noarch.rpm

# update system packages
$PKG update -y
# install requirements
$PKG install -y openssl ansible git vim

# if target system is a VM, we install a userland random number generator to enhance entropy
if systemd-detect-virt --vm -q && ! systemctl status haveged &> /dev/null; then
    echo "VM detected: installing haveged to enhance system entropy"
    $PKG install -y haveged &>> "$LOGFILE"
    systemctl enable haveged
    systemctl start haveged
    rgm_log "SYS: we detected running on a VM. install and configure 'haveged' daemon to enhance system entropy"
fi

# Install Ansible collections
ansible-galaxy collection install community.mysql


#    echo -e "This will install \e[34mRGM\e[39m with \e[1msubscription\e[0m for \e[92m$RGMP12\e[0m\n"
if [ -n "$RGMP12" ]; then
    TEMPDIR=$(mktemp -d)
    P12PWD=
    $PKG install -y bed-client
    if [ ! -f "$RGMP12" ]; then
        echo "\e[31mERROR\e[0m : PKCS#12 file \e[92m$RGMP12\e[0m not found. Installation aborted"
        rgm_log "EXIT FAIL: PKCS#12 file $RGMP12 not found. Installation aborted"
        exit 1
    fi

#    if [ ! -f "$RGMP12" ]; then
#        curl -s -L -k "${RGM_INSTALLER_URI}/pkcs12/${RGMP12}.p12" -o "${TEMPDIR}/${RGMP12}.p12"
#        rgm_log "PKI: retrieved customer PKCS12 certificate ${RGMP12} file"
#        RGMP12="${TEMPDIR}/${RGMP12}.p12"
#    fi

    while true; do
        echo "Please type in your PKCS12 password you received by email :"
        read -r -s P12PWD
        if openssl pkcs12 -in "${RGMP12}" -password "pass:${P12PWD}" -nodes -nokeys -cacerts -out /etc/pki/tls/certs/noc-rgm.pem; then
            break;
        fi
    done
    openssl pkcs12 -in "${RGMP12}" -password "pass:${P12PWD}" -nodes -nokeys -clcerts -out "${TEMPDIR}/client.pem"
    COMMON_NAME=$(openssl x509 -in "${TEMPDIR}/client.pem" -noout -subject | sed -E 's~.*/CN=(.+)(/.*)|$~\1~')
    mv "${TEMPDIR}/client.pem" "/etc/pki/tls/certs/${COMMON_NAME}.crt"
    openssl pkcs12 -in "${RGMP12}" -password "pass:${P12PWD}" -nodes -nocerts -out "/etc/pki/tls/private/${COMMON_NAME}.key"
    chmod 0664 /etc/pki/tls/certs/noc-rgm.pem "/etc/pki/tls/certs/${COMMON_NAME}.crt"
    chmod 0440 "/etc/pki/tls/private/${COMMON_NAME}.key"
    rgm_log "PKI: installed customer certificate on /etc/pki/tls/certs/${COMMON_NAME}.crt"
    rgm_log "PKI: installed customer key on/etc/pki/tls/private/${COMMON_NAME}.key"
    ln -s "/etc/pki/tls/certs/${COMMON_NAME}.crt" /etc/pki/tls/certs/rgmb.crt
    ln -s "/etc/pki/tls/private/${COMMON_NAME}.key" /etc/pki/tls/private/rgmb.key
    ln -s "/etc/pki/tls/certs/${COMMON_NAME}.crt" /var/lib/bed/certs/bed.pem

    ENABLE_BUSINESS=1
    rm -Rf "${TEMPDIR}"

    # enable RGM business repo
    pkg_config_manager 'enable' 'rgm-business-stable'
fi


# download Ansible playbook & roles
INSTALL_PLAY=0
if [ $ASSUMEYES -eq 1 ]; then
    ask_yesno "Ok to download and run \e[1;34mRGM\e[39m Ansible playbook\e[0m ? (y/\e[1mN\e[0m)"
    INSTALL_PLAY=$?
fi
if [ $INSTALL_PLAY -eq 0 ]; then
    if [ -e "${ANSIBLE_RGM_DIR}" ]; then
        rm -Rf "${ANSIBLE_RGM_DIR}"
    fi

    # workaround this unsafe certificate with Git. Not needed anymore as RGM ansible stuff is hosted on Github
    # git config --global http.sslVerify false
    # git config --global http.sslCAPath /etc/pki/tls/certs

    if [ -n "$PROXY" ]; then
        git config --global http.proxy "http://${PROXY_HOST}:${PROXY_PORT}"
        rgm_log "GIT: an HTTP proxy: http://${PROXY_HOST}:${PROXY_PORT}"
    fi

    # git clone RGM ansible roles & playbooks - or yum install rgm-ansible ?
    if ! cd "${HOME}"; then
        echo -e "\e[1;97;41mFailed to cwd to '$HOME'. Aborting.\e[0m"
        exit 1
    fi
    echo "Cloning Ansible RGM playbook from $RGM_ANSIBLE_REPO"
    rgm_log "GIT: cloning $RGM_ANSIBLE_REPO"
    if ! git clone -b $GIT_BRANCH_MASTER "${RGM_ANSIBLE_REPO}" "${ANSIBLE_RGM_DIR}" > /dev/null; then
        echo -e "\e[1;97;41mFailed to clone Git repo. Please check Internet connectivity and try again\e[0m"
        rgm_log "EXIT FAIL: failed to clone git repo"
        exit 1
    fi

    # checkout 'dev' branch if requested by command line
    if [ $CLONEDEV -eq 0 ]; then
        if ! cd "$ANSIBLE_RGM_DIR"; then
            echo -e "\e[1;97;41mFailed to cwd to '$ANSIBLE_RGM_DIR'. Aborting.\e[0m"
            exit 1
        fi
        echo "developpement release requested: switching to 'dev' branch"
        rgm_log "GIT: checking out 'dev' branch from $(basename $RGM_ANSIBLE_REPO)"
        ANSIBLE_ROLE_REQS='requirements-dev.yml'
        git checkout $GIT_BRANCH_RAWHIDE
        # shellcheck disable=SC2164
        cd -
    fi

    mkdir -p /etc/rgm/ansible
    ln -s /etc/rgm/ansible "${ANSIBLE_RGM_DIR}/host_vars/localhost"
    if [ ! -e /etc/rgm/ansible/localhost.yml ]; then
        cp "${ANSIBLE_RGM_DIR}/localhost.example.yml" /etc/rgm/ansible/localhost.yml
        chown root:root /etc/rgm/ansible/localhost.yml
        chmod 0640 /etc/rgm/ansible/localhost.yml
    fi

    if [ ${ENABLE_BUSINESS} -eq 1 ]; then
        if grep 'rgm_business_registration_id:' "${ANSIBLE_RGM_DIR}/host_vars/localhost/localhost.yml" &> /dev/null; then
            sed -i "s|^\(#\s*\)*rgm_business_registration_id:.*$|rgm_business_registration_id: '${COMMON_NAME}'|" "${ANSIBLE_RGM_DIR}/host_vars/localhost/localhost.yml"
        else
            echo "rgm_business_registration_id: '${COMMON_NAME}'" >> "${ANSIBLE_RGM_DIR}/host_vars/localhost/localhost.yml"
        fi
        SKIPTAGS=''
    fi

    if [ $AUTOPART -eq 0 ]; then
        echo "running auto-partitionner. Will assign any unused drive to RGM usage !"
        generate_disk_partition
    else
        echo -e "\n\e[1mAuto-partitioning \e[31mdisabled\e[0m per user request."
        echo -e "\e[1;34mRGM\e[39m installation will perform on a flat partition\e[0m"
    fi
    if [ -n "$PROXY" ]; then
        echo "configure RGM to use proxy ${PROXY_HOST}:${PROXY_PORT}"
        add_or_upate '^(#\s*)?proxy_host:.*$' "proxy_host: ${PROXY_HOST}" "${ANSIBLE_RGM_DIR}/host_vars/localhost/localhost.yml"
        add_or_upate '^(#\s*)?proxy_port:.*$' "proxy_port: ${PROXY_PORT}" "${ANSIBLE_RGM_DIR}/host_vars/localhost/localhost.yml"
        rgm_log "ANSIBLE: add proxy variables to rgm group_vars: ${PROXY_HOST}:${PROXY_PORT}"
    fi

    if [ -n "${COMMERCIALS[*]}" ]; then
        for COMMERCIAL in ${COMMERCIALS[*]}; do
            echo "configure RGM to enable partner packages for $COMMERCIAL"
            add_or_upate "^(#\s*)?install_commercial_${COMMERCIAL}:.*$" "install_commercial_${COMMERCIAL}: true" "${ANSIBLE_RGM_DIR}/host_vars/localhost/localhost.yml"
            rgm_log "ANSIBLE add  \"install_commercial_${COMMERCIAL}: true\" to rgm group_vars"
        done
    fi

    if [ $VARSREVIEW -eq 0 ]; then
        echo -e "\n\e[1m Before running the Ansible playbook, you can have a review of ansible 'host vars' file.\n" \
        "You can make some modifications in this file to customize your RGM installation to fit\n" \
            "your specific needs, like:\n" \
            " - customizing SNMP settings (community, location, contact,...)\n" \
            " - customizing the Apache HTTPd SSL/TLS configuration (eg. adding your own certificate)\n" \
            " - customizing storage partitionning\e[0m\n"
        if ask_yesno "Review Ansible \e[1mvars\e[0m file ? (y/\e[1mN\e[0m)"; then
            vim "${ANSIBLE_RGM_DIR}/host_vars/localhost/localhost.yml"
        fi
    fi

    # stop here if no ansible
    if [ $NOANSIBLE -eq 0 ]; then
        echo -e "\nNo ansible execution requested. stop here."
        echo "To install or update Ansible roles, type the following commands:"
        echo ""
        echo -e "\e[1m ansible-galaxy install -f -p ${ANSIBLE_RGM_DIR}/roles -r ${ANSIBLE_RGM_DIR}/roles/${ANSIBLE_ROLE_REQS}\e[0m\n"
        echo -e "\e[1m cd ${ANSIBLE_RGM_DIR} && ansible-playbook rgm-installer.yml\e[0m\n"
    else
        if ! cd "${ANSIBLE_RGM_DIR}"; then
            echo -e "\e[1;97;41mFailed to cwd to '$ANSIBLE_RGM_DIR'. Aborting.\e[0m"
            exit 1
        fi
        if ! ansible-galaxy role install -p "${ANSIBLE_RGM_DIR}/roles" -r "${ANSIBLE_RGM_DIR}/roles/${ANSIBLE_ROLE_REQS}"; then
            echo "\e[1;97;41mFailed to clone Git repo. Please check Internet connectivity and try again\e[0m"
            rgm_log "EXIT FAIL: failed to install Ansible roles requirements (ansible-galaxy)"
            exit 1
        fi
        if ! ansible-galaxy collection install -r "${ANSIBLE_RGM_DIR}/roles/${ANSIBLE_ROLE_REQS}"; then
            echo "\e[1;97;41mFailed to install Ansible collections from galaxy. Please check Internet connectivity and try again\e[0m"
            rgm_log "EXIT FAIL: failed to install Ansible collections requirements (ansible-galaxy)"
            exit 1
        fi

        # generates a random password for RGM user if the user doesn't exists yet
        if ! getent passwd rgm &> /dev/null; then
            RGMPWD="$(head -c 1024 /dev/urandom | tr -cd _A-Z-a-z-0-9 | fold -w16 | head -n1)"
            add_extra_var "rgm_user_password=${RGMPWD}"
            rgm_log "SYS: a password was randomly generated for system user [rgm]"
        fi

        # run Ansible locally
        rgm_log "ANSIBLE: running ansible-playbook ${EXTRAVARS[*]} rgm-installer.yml"
        ansible-playbook "${EXTRAVARS[@]}" rgm-installer.yml ${SKIPTAGS}
        RC=$?
        if [ $RC -eq 0 ]; then
            DEFNIC=$(ip route | grep ^default | awk '{print $5}')
            IPADDR=$(ip addr show "$DEFNIC" | grep 'inet ' | awk '{print $2}' | cut -d '/' -f 1)
            echo -en "\nYou can access the \e[34;1mRGM\e[0m web interface by pointing your browser to \e[1mhttps://$IPADDR/\e[0m"
            if host "$IPADDR" &> /dev/null; then
                echo -en "or \e[1mhttps://$(host "${IPADDR}" | awk '{print $5}')/\e[0m"
            fi
            echo -e "\nThe default 'admin' password is '\e[1madmin\e[0m'. \e[31;1mPlease change it as soon as possible !\e[0m"
            if [ -z "$RGMPWD" ]; then
                echo -e "\nThe SSH access is using user 'rgm' with \e[1myour\e[0m password."
            else
                echo -e "\nThe SSH access is using user 'rgm' with password '\e[1m${RGMPWD}\e[0m'."
            fi
        fi
    fi
fi


echo -e "\nHope you'll enjoy \e[1;34mRGM\e[0m !"
echo -e "For documentation and support, please visit our website:"
echo -e "\n\e[1m $RGM_WEBSITE\e[0m\n"

exit $RC
# vim: expandtab sw=4 ts=4:
