#!/bin/bash

set -oux pipefail

# shellcheck disable=SC1091
#
# Copyright 2023 The qm Authors
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; If not, see <http://www.gnu.org/licenses/>.
#
# Capture the start time
START_TIME=$(date +%s)
SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )

# shellcheck disable=SC1091
source "${SCRIPT_DIR}"/lib/utils
# shellcheck disable=SC1091
source "${SCRIPT_DIR}"/lib/container
# shellcheck disable=SC1091
source "${SCRIPT_DIR}"/lib/systemd
# shellcheck disable=SC1091
source "${SCRIPT_DIR}"/lib/tests
# shellcheck disable=SC1091
source "${SCRIPT_DIR}"/lib/diskutils
# shellcheck disable=SC1091
source "${SCRIPT_DIR}"/lib/repoutils

# GLOBALS
export CONFIG_NODE_AGENT_PATH="/etc/bluechi/agent.conf.d/agent.conf"
export REGISTRY_UBI8_MINIMAL="registry.access.redhat.com/ubi8/ubi-minimal"
export WAIT_BLUECHI_SERVER_BE_READY_IN_SEC=5
export CONTROL_CONTAINER_NAME="control"
export NODES_FOR_TESTING=("control" "node1")
export IP_CONTROL_MACHINE=""
export CONTAINER_CAP_ADD=""
export ARCH=""
export DISK=""
export PART_ID=""
export QC_SOC="${QC_SOC_TYPE:-SA8775P}"
export SOC_DISTRO_FILE="${SOC_FILE:-/sys/devices/soc0/machine}"
export QC_SOC_DISK="${QC_DISK_NAME:-sde}"
export OS_DISTRO="${CS_DISTRO:-}"
export QM_CTR_CFG="${QM_CNTR_CONFIG:-/etc/qm/containers/containers.conf}"
export U_NOFILE_PRCTG=${NOFILE_RATIO:-50}
export U_NPROC_PRCTG=${NPROC_RATIO:-75}


export BUILD_BLUECHI_FROM_GH_URL=""
export QM_GH_URL=""
export BRANCH_QM=""
export SET_QM_PART=""
export USE_QM_COPR="${PACKIT_COPR_PROJECT:-rhcontainerbot/qm}"

RED='\033[91m'
GRN='\033[92m'
CLR='\033[0m'

# ====================== Start - int main {} ;-)
ARGUMENT_LIST=(
    "qm-setup-from-gh-url"
    "branch-qm"
    "set-qm-disk-part"
    "use-qm-copr"
)

usage() {
cat <<EOF
Usage: ./set-ffi-env-e2e [OPTIONS]

--help
	This message

--qm-setup-from-gh-url
        Override QM setup QM from a specific GitHub URL, useful for testing new features

--branch-qm
        Specify which branch the GitHub repo will be set. Requires --qm-setup-from-gh-url

--set-qm-disk-part
        Specify if disk partition neede for /var/qm needed

--use-qm-copr
        Specify to install rpms from rhcontainerbot/qm copr

Examples:

	No args, it will install latest qm and bluechi from copr rpm repository
		./set-ffi-env-e2e

        Use qm setup specific github url and select the branches
                ./set-ffi-env-e2e \\
                        --branch-qm=superfeature \\
                        --qm-setup-from-gh-url=https://raw.githubusercontent.com/MYUSER/ \\
                        --set-qm-disk-part=Y \\
                        --use-qm-copr=Y \\

EOF
    exit 0
}

# read arguments
opts=$(getopt \
    --longoptions "$(printf "help,%s:," "${ARGUMENT_LIST[@]}")" \
    --name "$(basename "$0")" \
    --options "" \
    -- "$@"
)

eval set --"${opts}"

while [ $# -gt 0 ]; do
    case "$1" in
        --branch-qm)
            BRANCH_QM="${2}"
            shift 2
            ;;

        --qm-setup-from-gh-url)
            if [ -z "${BRANCH_QM}" ]; then
                BRANCH_QM="main"
            fi
            QM_GH_URL="${2}/qm/${BRANCH_QM}/setup"
            shift 2
            ;;

        --set-qm-disk-part)
            SET_QM_PART="${2}"
            shift 2
            ;;

        --use-qm-copr)
            USE_QM_COPR="${2}"
            shift 2
            ;;

        --help)
            usage
            ;;

        *)
            break
            ;;
    esac
done

setup_qm_services() {

  info_message "Setup qm services"
  info_message "=============================="

  #Update setup script from QM repos, in case rpm not updates yet
  if [ -n "${QM_GH_URL}" ]; then
      curl "${QM_GH_URL}"  > /usr/share/qm/setup
      chmod +x /usr/share/qm/setup
  fi
  # Curl files into here,
  # Fix: default setup:main should be removed on next qm release
  /usr/share/qm/setup --hostname localrootfs
  # Update QM relimits
  set_qm_rlimits
  cat > /etc/bluechi/controller.conf << 'EOF'
[bluechi-controller]
AllowedNodeNames=qm.localrootfs,localrootfs
ControllerPort=842
LogLevel=INFO
LogTarget=journald
LogIsQuiet=false
EOF
cat > /etc/bluechi/agent.conf.d/00-default.conf << 'EOF'
[bluechi-agent]
NodeName=localrootfs
EOF

controller_host_ip=$(hostname -I | awk '{print $1}')
qm_bluechi_agent_config_file="/etc/qm/bluechi/agent.conf.d/agent.conf"
if [[ -f "${qm_bluechi_agent_config_file}" ]]; then
    if ! grep "ControllerHost=${controller_host_ip}" "${qm_bluechi_agent_config_file}" >/dev/null; then
        sed -i '$a \ControllerHost='"${controller_host_ip}"'' ${qm_bluechi_agent_config_file}
    fi
else
    echo "Configuration file not found: ${qm_bluechi_agent_config_file}"
fi

  # Enable services
  info_message "Setup qm services, enable bluechi services"
  info_message "=============================="
  systemctl enable bluechi-controller
  systemctl enable bluechi-agent
  # Start services
  info_message "Setup qm services, start bluechi services"
  info_message "=============================="
  systemctl start bluechi-controller
  systemctl start bluechi-agent
  # Restart qm to read lates bluechi-agent.conf
  systemctl restart qm
}

info_message "Starting setup"
info_message "=============================="
if [ "$EUID" -ne 0 ]
then
    echo -e "[${RED} ERROR ${CLR}] Please run as root this script. It requires to set limits inside a container which is not allowed by root."
    exit
fi

if stat /run/ostree-booted > /dev/null 2>&1; then
   info_message "Warning: script can not run on ostree image"
   info_message "=============================="
   exit 0
fi

# Creates  partitions for QM env on VM
echo
info_message "Check if qm requires additional partition"
info_message "=============================="
if [ -n "${SET_QM_PART}" ]; then
    create_qm_var_part
fi

echo
info_message "Checking if QM already installed"
info_message "=============================="
if rpm -q qm &>/dev/null; then
	QM_STATUS="$(systemctl is-enabled qm 2>&1)"
        if test /etc/os-release; then
             OS_DISTRO=$(grep -oP '(?<=^ID=)\w+' <<< "$(tr -d '"' < /etc/os-release)")
        fi
	if [ "$QM_STATUS" == "generated" ]; then
		if [ "$(systemctl is-active qm)" == "active" ]; then
			info_message "QM Enabled and Active"
			info_message "=============================="
			exit 0
   		fi
		if test -d /var/qm -a -d /etc/qm -a -z "$OS_DISTRO" ; then
			info_message "QM Enabled and not Active"
			info_message "=============================="
			exit 1
   		fi
	fi
fi

info_message "Cleaning any previous e2e files"
info_message "=============================="
cleanup

echo
info_message "Preparing QM environment"
info_message "=============================="

install_qm_rpms
setup_qm_services

info_message "${GRN}QM environment${CLR}"
info_message "=============================="

# Capture the end time
END_TIME=$(date +%s)

# Calculate the duration in seconds
DURATION=$((END_TIME - START_TIME))

# Calculate minutes and seconds
DAYS=$((DURATION / 86400))
HOURS=$(( (DURATION % 86400) / 3600 ))
MINUTES=$(( (DURATION % 3600) / 60 ))
SECONDS=$((DURATION % 60))

info_message "${GRN}Running time for this script${CLR}"
info_message "\t- ${DAYS} days, ${HOURS} hours, ${MINUTES} minutes and ${SECONDS} seconds"
info_message "All set!"
info_message "=============================="
