#!/bin/bash

#export PANDORA_SERVER_IP='newdemos.artica.es' && curl -sSL https://packages.pandorafms.com/projects/pandora_deploy_agent.sh | bash

# define variables
PANDORA_AGENT_CONF=/etc/pandora/pandora_agent.conf
S_VERSION='2608.1'
LOGFILE="/tmp/pandora-agent-deploy-$(date +%F).log"

# Ansi color code variables
red=$'\e[0;91m'
green=$'\e[0;92m'
bold=$'\e[1m'
cyan=$'\e[0;36m'
yellow=$'\e[33m'
reset=$'\e[0m'

# Default values
[ "$RHEL_CHECK_SUBSCRIPTION" ] || RHEL_CHECK_SUBSCRIPTION=1

# Agent package type: GO, PERL, or PERL_SOURCES.
# - When PANDORA_AGENT_PACKAGE is not defined, it acts as the type selector for
#   the default tarball.
# - When PANDORA_AGENT_PACKAGE is a direct http(s):// URL, the URL is used as-is
#   and this variable only selects the dependencies to install (default GO).
[ "$PANDORA_AGENT_PACKAGE_TYPE" ] || PANDORA_AGENT_PACKAGE_TYPE="GO"

# Release channel: STABLE (default) or BETA.
# STABLE pulls from .../latest, BETA pulls from .../nightlies.
[ "$PANDORA_AGENT_RELEASE" ] || PANDORA_AGENT_RELEASE="STABLE"
PANDORA_AGENT_RELEASE=$(echo "$PANDORA_AGENT_RELEASE" | tr '[:lower:]' '[:upper:]')

case "$PANDORA_AGENT_RELEASE" in
    STABLE)
        PANDORA_AGENT_PACKAGE_BASE_URL="https://packages.pandorafms.com/pandorafms/latest"
        PANDORA_AGENT_PACKAGE_SUFFIX="latest"
        ;;
    BETA)
        PANDORA_AGENT_PACKAGE_BASE_URL="https://packages.pandorafms.com/pandorafms/nightlies"
        PANDORA_AGENT_PACKAGE_SUFFIX="nightlies"
        ;;
    *)
        echo -e "${red}Error: PANDORA_AGENT_RELEASE value '$PANDORA_AGENT_RELEASE' is not valid.${reset}"
        echo -e "${red}Use one of: STABLE, BETA.${reset}"
        exit 1
        ;;
esac

# Default tarball URLs per agent type, parameterized by release channel.
PANDORA_AGENT_PACKAGE_GO="${PANDORA_AGENT_PACKAGE_BASE_URL}/pandorafms_one_agent_linux-${PANDORA_AGENT_PACKAGE_SUFFIX}.go.tar.gz"
PANDORA_AGENT_PACKAGE_PERL="${PANDORA_AGENT_PACKAGE_BASE_URL}/pandorafms_one_agent_linux-${PANDORA_AGENT_PACKAGE_SUFFIX}.tar.gz"
PANDORA_AGENT_PACKAGE_PERL_SOURCES="${PANDORA_AGENT_PACKAGE_BASE_URL}/pandorafms_one_agent_linux-${PANDORA_AGENT_PACKAGE_SUFFIX}.src.tar.gz"

# Local tarball filename used for the download.
PANDORA_AGENT_TARBALL="pandorafms_agent_linux.tar.gz"

#Check if possible to get os version
if [ ! -e /etc/os-release ]; then
    echo ' > Imposible to determinate the OS version for this machine, please make sure you are installing in a compatible OS'
    echo ' > More info: https://pandorafms.com/manual/en/documentation/02_installation/01_installing#minimum_software_requirements'
    exit 1
fi

# Functions

execute_cmd () {
    local cmd="$1"
    local msg="$2"

    echo -ne "${cyan}$msg...${reset}"
    $cmd &>> "$LOGFILE"
    if [ $? -ne 0 ]; then
        echo -e "${red}Fail${reset}"
        [ "$3" ] && echo "$3"
        echo "Error installing PandoraFMS for detailed error please check log: $LOGFILE"
        rm -rf "$HOME"/pandora_deploy_tmp &>> "$LOGFILE"
        exit 1
    else
        echo -ne "\r${cyan}$msg...${reset} ${green}OK${reset}\n"
        return 0
    fi
}

check_cmd_status () {
    if [ $? -ne 0 ]; then
        echo -e "${red}Fail${reset}"
        [ "$1" ] && echo "$1"
        echo "Error installing Pandora FMS Agent for detailed error please check log: $LOGFILE"
        rm -rf $HOME/pandora_deploy_tmp/*.tar.gz* &>> $LOGFILE
        exit 1
    else
        echo -e "${green}OK${reset}"
        return 0
    fi
}

check_repo_connection () {
    #execute_cmd "ping -c 2 packages.pandorafms.com" "Checking PandoraFMS repo"
    echo -en "${cyan}Checking PandoraFMS repositry ...${reset}"
    curl -SsL 'https://packages.pandorafms.com/pandorafms' | grep pandorafms &>> "$LOGFILE"
    check_cmd_status 'Error: unable to reach https://packages.pandorafms.com/pandorafms repository'
}

check_root_permissions () {
    echo -en "${cyan}Checking root account... ${reset}"
    if [ "$(whoami)" != "root" ]; then
        echo -e "${red}Fail${reset}"
        echo "Please use a root account or sudo for installing PandoraFMS"
        echo "Error installing Pandora FMS for detailed error please check log: $LOGFILE"
        exit 1

    else
        echo -e "${green}OK${reset}"
    fi
}

install_tarball () {
    local tarball="$1"
    local install_mode="$2"

    tar xvzf "$tarball" &>> "$LOGFILE"
    cd unix && ./pandora_agent_installer "$install_mode" &>> "$LOGFILE"
    local msg="Installing pandora agent"
    echo "${cyan}$msg...${reset} "
    echo -ne "\r${cyan}$msg...${reset} ${green}OK${reset}\n"
    return 0
}

confirm () {
    local message="$1"
    local response

    echo -e "${yellow}${message}${reset}"
    read -p "Are you sure you want to proceed? (Y/y to continue): " response </dev/tty

    if [[ "$response" == "Y" || "$response" == "y" ]]; then
        return 0
    else
        echo -e "${red}Aborted${reset}"
        exit 1
    fi
}

# Normalize a package type value to the canonical GO, PERL or PERL_SOURCES.
# Collapses case and aliases; on invalid input prints an error to stderr and
# returns non-zero (the caller must handle the failure).
resolve_package_type () {
    local pkg_type
    pkg_type=$(echo "$1" | tr '[:lower:]' '[:upper:]')

    case "$pkg_type" in
        GO)
            echo "GO"
            ;;
        PERL)
            echo "PERL"
            ;;
        PERL_SOURCES|PERLSOURCES|PERL_SRC|PERLSRC)
            echo "PERL_SOURCES"
            ;;
        *)
            echo -e "${red}Error: '${1}' is not a valid package type.${reset}" >&2
            echo -e "${red}Use one of: GO, PERL, PERL_SOURCES.${reset}" >&2
            return 1
            ;;
    esac
}

# Resolve the agent package URL based on PANDORA_AGENT_PACKAGE.
# - Warns in yellow when PANDORA_AGENT_RELEASE is BETA (nightlies channel).
# - If PANDORA_AGENT_PACKAGE is a direct http(s):// URL, use it as-is and warn
#   in yellow that the default package URL selection is skipped; dependencies
#   still follow PANDORA_AGENT_PACKAGE_TYPE (default GO).
# - Otherwise treat it as a type selector (GO, PERL, PERL_SOURCES) and map it
#   to the corresponding default tarball URL.
resolve_agent_package () {
    if [ "$PANDORA_AGENT_RELEASE" = "BETA" ]; then
        if [ "${PANDORA_SKIP_CONFIRMATION}" != "1" ]; then
            confirm "PANDORA_AGENT_RELEASE is set to BETA, installing from nightlies (${PANDORA_AGENT_PACKAGE_BASE_URL})."
        else
            echo -e "${yellow}PANDORA_AGENT_RELEASE is set to BETA, installing from nightlies (${PANDORA_AGENT_PACKAGE_BASE_URL}).${reset}"
        fi
    fi

    if [[ "$PANDORA_AGENT_PACKAGE" =~ ^https?:// ]]; then
        echo -e "${yellow}PANDORA_AGENT_PACKAGE is a direct URL, default package selection (GO/PERL/PERL_SOURCES) is skipped; the URL is used as-is.${reset}"
        echo -e "${yellow}Dependencies will follow PANDORA_AGENT_PACKAGE_TYPE (default GO).${reset}"
        if [ "$ARCH_REQUIRES_SOURCES" -eq 1 ]; then
            echo -e "${yellow}WARNING: arch ${arch} requires a source build, but a direct URL was provided. Make sure the tarball contains source code, not a pre-compiled binary.${reset}"
        fi
        PANDORA_AGENT_PACKAGE_URL="$PANDORA_AGENT_PACKAGE"
        PANDORA_AGENT_RESOLVED_TYPE="$(resolve_package_type "$PANDORA_AGENT_PACKAGE_TYPE")" || exit 1
        return 0
    fi

    local pkg_type
    pkg_type=$(resolve_package_type "$PANDORA_AGENT_PACKAGE") || exit 1

    # On non-x86_64 archs, binary agents (GO/PERL) won't work. Override to
    # PERL_SOURCES unless the user already selected it.
    if [ "$ARCH_REQUIRES_SOURCES" -eq 1 ] && [ "$pkg_type" != "PERL_SOURCES" ]; then
        echo -e "${yellow}Overriding PANDORA_AGENT_PACKAGE from ${pkg_type} to PERL_SOURCES for arch ${arch}.${reset}"
        pkg_type="PERL_SOURCES"
    fi

    case "$pkg_type" in
        GO)
            PANDORA_AGENT_PACKAGE_URL="$PANDORA_AGENT_PACKAGE_GO"
            PANDORA_AGENT_RESOLVED_TYPE="GO"
            ;;
        PERL)
            PANDORA_AGENT_PACKAGE_URL="$PANDORA_AGENT_PACKAGE_PERL"
            PANDORA_AGENT_RESOLVED_TYPE="PERL"
            ;;
        PERL_SOURCES)
            PANDORA_AGENT_PACKAGE_URL="$PANDORA_AGENT_PACKAGE_PERL_SOURCES"
            PANDORA_AGENT_RESOLVED_TYPE="PERL_SOURCES"
            ;;
    esac
}

# Validate that the downloaded tarball is a real Pandora FMS agent package.
# Two layers:
#  (a) Structural: required entries exist in the tarball.
#  (b) Fingerprint: the installer header contains the Pandora FMS mark.
# Aborts with a red error and cleanup if any layer fails.
validate_agent_tarball () {
    local tarball="$1"
    local url="$2"
    local missing=0

    echo -en "${cyan}Validating agent tarball... ${reset}"

    # Layer (a): structural check.
    local entries
    entries=$(tar tzf "$tarball" 2>> "$LOGFILE")
    if [ $? -ne 0 ]; then
        echo -e "${red}Fail${reset}"
        echo -e "${red}Error: the downloaded tarball does not look like a valid Pandora FMS agent.${reset}"
        echo -e "${red}Could not list tarball contents. Downloaded URL: $url${reset}"
        rm -rf "$HOME"/pandora_deploy_tmp &>> "$LOGFILE"
        exit 1
    fi

    for required in unix/pandora_agent_installer unix/pandora_agent unix/tentacle_client; do
        if ! echo "$entries" | grep -q "^${required}$"; then
            missing=1
        fi
    done

    if [ "$missing" -eq 1 ]; then
        echo -e "${red}Fail${reset}"
        echo -e "${red}Error: the downloaded tarball does not look like a valid Pandora FMS agent.${reset}"
        echo -e "${red}Missing expected files (unix/pandora_agent_installer, unix/pandora_agent, unix/tentacle_client).${reset}"
        echo -e "${red}Downloaded URL: $url${reset}"
        rm -rf "$HOME"/pandora_deploy_tmp &>> "$LOGFILE"
        exit 1
    fi

    # Layer (b): content fingerprint.
    if ! tar xzf "$tarball" -O unix/pandora_agent_installer 2>> "$LOGFILE" | grep -q "Pandora FMS Agent Installer for Unix"; then
        echo -e "${red}Fail${reset}"
        echo -e "${red}Error: the downloaded tarball does not look like a valid Pandora FMS agent.${reset}"
        echo -e "${red}Installer fingerprint mismatch (missing 'Pandora FMS Agent Installer for Unix').${reset}"
        echo -e "${red}Downloaded URL: $url${reset}"
        rm -rf "$HOME"/pandora_deploy_tmp &>> "$LOGFILE"
        exit 1
    fi

    echo -e "${green}OK${reset}"
}

## Main
echo "Starting PandoraFMS Agent deployment ver. $S_VERSION"

execute_cmd  "[ $PANDORA_SERVER_IP ]" 'Check Server IP Address' 'Please define env variable PANDORA_SERVER_IP'

if ! grep --version &>> $LOGFILE ; then echo 'Error grep is not detected on the system, grep tool is needed for installation.'; exit 1 ;fi
if ! sed --version &>> $LOGFILE ; then echo 'Error sed is not detected on the system, sed tool is needed for installation.'; exit 1 ;fi

# Detect OS family and version from /etc/os-release.
os_name=$(grep ^PRETTY_NAME= /etc/os-release | cut -d '=' -f2 | tr -d '"')
os_id=$(grep ^ID= /etc/os-release | cut -d '=' -f2 | tr -d '"')
os_id_like=$(grep ^ID_LIKE= /etc/os-release 2>/dev/null | cut -d '=' -f2 | tr -d '"')
os_major=$(grep ^VERSION_ID= /etc/os-release | cut -d '=' -f2 | tr -d '"' | cut -d '.' -f1)
execute_cmd "echo $os_name" "OS detected: ${os_name}"

# Single exclusive case statement for OS family detection.
# OS_RELEASE is kept as the variable name for backwards compatibility with
# the rest of the script (dependency install branches check OS_RELEASE).
case "$os_id $os_id_like" in
    *rhel*|*fedora*|*centos*|*rocky*|*almalinux*|*ol*)
        OS_RELEASE="rhel"
        ;;
    *debian*|*ubuntu*)
        OS_RELEASE="debian"
        ;;
    *suse*|*opensuse*)
        OS_RELEASE="suse"
        ;;
    *)
        echo -e "${red}Error: unsupported OS '${os_name}'.${reset}"
        echo -e "${red}Supported: RHEL/CentOS/Rocky/Alma 7-10, SUSE/OpenSUSE, Debian/Ubuntu 22.04+.${reset}"
        exit 1
        ;;
esac

# initialice logfile
execute_cmd "echo 'Starting deployment' > $LOGFILE" "All installer activity is logged on $LOGFILE"
echo "Enterprise installer version: $S_VERSION" >> $LOGFILE

# Pre checks
echo -e "${cyan}Checking compatible OS... ${reset}${green}OK${reset} (${OS_RELEASE})"

# Root permisions
check_root_permissions

# Connectivity
check_repo_connection

# Execute tools check
execute_cmd "grep --version" 'Checking needed tools: grep'
execute_cmd "sed --version" 'Checking needed tools: sed'
execute_cmd "curl --version" 'Checking needed tools: curl'

# Arch check
arch=$(uname -m)
ARCH_REQUIRES_SOURCES=0
case $arch in

  x86_64)
    echo -e "${cyan}Arch: $arch ${reset} "
    ;;

  x86|armv7l|aarch64)
    echo -e "${yellow}Arch: $arch is not supported by the binary agent, switching to PERL_SOURCES (source build).${reset}"
    ARCH_REQUIRES_SOURCES=1
    ;;

  *)
    echo -e "${yellow}Skipping installation: arch $arch not supported. Consider installing the source agent manually.${reset}"
    exit 1
    ;;
esac

# Resolve the agent package URL.
# PANDORA_AGENT_PACKAGE may be a type (GO, PERL, PERL_SOURCES) or a direct URL.
# If not set, fall back to PANDORA_AGENT_PACKAGE_TYPE (default GO).
if [ ! "$PANDORA_AGENT_PACKAGE" ]; then
    PANDORA_AGENT_PACKAGE="$PANDORA_AGENT_PACKAGE_TYPE"
fi
resolve_agent_package
echo -e "${cyan}Agent package: ${reset}${PANDORA_AGENT_PACKAGE_URL}"

# Creating working directory
rm -rf $HOME/pandora_deploy_tmp/ &>> $LOGFILE
mkdir $HOME/pandora_deploy_tmp &>> $LOGFILE
execute_cmd "cd $HOME/pandora_deploy_tmp" "Moving to workspace:  $HOME/pandora_deploy_tmp"

# Installing dependencies and downloading the agent tarball.
# The install path is always tarball-based for every supported OS.

if [ "$PANDORA_SKIP_DEPENDENCIES" != "1" ]; then
    if [[ $OS_RELEASE =~ 'rhel' ]] || [[ $OS_RELEASE =~ 'fedora' ]]; then
        ## Extra steps on redhat
        if [ "$RHEL_CHECK_SUBSCRIPTION" -eq '1' ] &&  ! grep -qEi 'Oracle Linux' /etc/os-release ; then
            if [ "$(grep -Ei 'Red Hat Enterprise' /etc/redhat-release)" ]; then
                ## In case REDHAT
                # Check susbscription manager status:
                echo -en "${cyan}Checking Red Hat Enterprise subscription... ${reset}"
                subscription-manager list &>> "$LOGFILE"
                subscription-manager status &>> "$LOGFILE"
                check_cmd_status 'Error checking subscription status, make sure your server is activated and suscribed to Red Hat Enterprise repositories'

            fi
        fi

        # Install OS-specific dependencies based on major version (os_major extracted from VERSION_ID).
        if [ "$os_major" -eq '7' ] ; then
            package_manager_cmd=yum
        elif [ "$os_major" -eq '8' ] ; then
            package_manager_cmd=dnf
        elif [ "$os_major" -eq '9' ] ; then
            package_manager_cmd=dnf
        elif [ "$os_major" -eq '10' ] ; then
            package_manager_cmd=dnf
        else
            package_manager_cmd=dnf
        fi

        # Install agent dependencies based on agent type.
        case "$PANDORA_AGENT_RESOLVED_TYPE" in
            GO)
                execute_cmd "$package_manager_cmd install -y perl tar" "Installing Go agent dependencies"
                ;;
            PERL)
                if [ "$os_major" -eq '8' ] ; then
                    execute_cmd "$package_manager_cmd install -y libnsl" "Installing dependencies"
                elif [ "$os_major" -eq '9' ] || [ "$os_major" -eq '10' ] ; then
                    execute_cmd "$package_manager_cmd install -y libnsl libxcrypt-compat" "Installing dependencies"
                fi
                execute_cmd "$package_manager_cmd install -y perl perl-Sys-Syslog unzip tar" "Installing Perl agent dependencies"
                ;;
            PERL_SOURCES)
                if [ "$os_major" -eq '9' ] || [ "$os_major" -eq '10' ] ; then
                    execute_cmd "$package_manager_cmd install -y libxcrypt-compat perl-Thread-Semaphore" "Installing dependencies"
                fi
                execute_cmd "$package_manager_cmd install -y perl perl-Scalar-List-Utils perl-Sys-Syslog perl-IO-Socket-SSL perl-Digest-MD5 perl-threads perl-threads-shared  libnsl unzip tar" "Installing Perl sources agent dependencies"
                ;;
            *)
                execute_cmd "$package_manager_cmd install -y perl perl-Sys-Syslog unzip tar" "Installing agent dependencies"
                ;;
        esac

    fi

    if [[ $OS_RELEASE == 'suse' ]]; then
        case "$PANDORA_AGENT_RESOLVED_TYPE" in
            GO)
                execute_cmd "zypper install -y perl tar" 'Installing Go agent dependencies'
                ;;
            PERL)
                execute_cmd "zypper install -y perl unzip tar" 'Installing Perl agent dependencies'
                ;;
            PERL_SOURCES)
                execute_cmd "zypper install -y perl perl-YAML-Tiny perl-IO-Socket-SSL libnsl3 unzip tar" 'Installing Perl sources agent dependencies'
                ;;
            *)
                execute_cmd "zypper install -y perl unzip tar" 'Installing agent dependencies'
                ;;
        esac
    fi

    if [[ $OS_RELEASE == 'debian' ]]; then
        execute_cmd "apt update" 'Updating repos'
        case "$PANDORA_AGENT_RESOLVED_TYPE" in
            GO)
                execute_cmd "apt install -y perl procps tar" 'Installing Go agent dependencies'
                ;;
            PERL)
                execute_cmd "apt install -y perl unzip procps tar" 'Installing Perl agent dependencies'
                ;;
            PERL_SOURCES)
                execute_cmd "apt install -y perl libsys-syslog-perl libyaml-tiny-perl libio-socket-ssl-perl libscalar-list-utils-perl unzip procps tar" 'Installing Perl sources agent dependencies'
                ;;
            *)
                execute_cmd "apt install -y perl unzip procps tar" 'Installing agent dependencies'
                ;;
        esac
    fi
fi

# Download the agent tarball (always tarball, never RPM).
execute_cmd "curl -LSs --output ${PANDORA_AGENT_TARBALL} ${PANDORA_AGENT_PACKAGE_URL}" "Downloading Pandora FMS agent tarball"

# Validate the downloaded tarball is a real Pandora FMS agent before installing.
validate_agent_tarball "$PANDORA_AGENT_TARBALL" "$PANDORA_AGENT_PACKAGE_URL"

# Determine install mode and detect existing installations.
INSTALL_MODE="--install"
if [ -f /usr/bin/pandora_agent ] || [ -d /usr/share/pandora_agent ] || [ -f /etc/pandora/pandora_agent.conf ]; then
    echo -e "${yellow}Existing installation detected, updating...${reset}"
    INSTALL_MODE="--force-install"
fi

# Install the agent from the tarball.
install_tarball "${PANDORA_AGENT_TARBALL}" "$INSTALL_MODE"
execute_cmd "test -f ${PANDORA_AGENT_CONF}" "Validating Pandora FMS agent installation"

cd $HOME/pandora_deploy_tmp

# The tarball installer finishes by starting the service (systemctl enable --now),
# so the agent is already running against the default configuration. On first boot
# the Go agent rewrites the conf in place (agent_name_cmd __rand__ -> configUpdate,
# a non-atomic read-modify-write), which races with the sed substitutions below and
# can revert server_ip to localhost. Stop the agent and wait for the process to exit
# so the sed is the only writer; the service is started again further down.
if command -v systemctl >/dev/null 2>&1 && systemctl list-unit-files pandora_agent_daemon.service >/dev/null 2>&1; then
    systemctl stop pandora_agent_daemon &>> "$LOGFILE"
elif [ -x /etc/init.d/pandora_agent_daemon ]; then
    /etc/init.d/pandora_agent_daemon stop &>> "$LOGFILE"
fi
pkill -x pandora_agent &>> "$LOGFILE"
for _ in {1..20}; do
    pgrep -x pandora_agent >/dev/null 2>&1 || break
    sleep 0.5
done

# Configuring Agente
[[ $PANDORA_SERVER_IP ]] && sed -i "s/^server_ip.*$/server_ip $PANDORA_SERVER_IP/g" $PANDORA_AGENT_CONF
[[ $PANDORA_REMOTE_CONFIG ]] && sed -i "s/^remote_config.*$/remote_config $PANDORA_REMOTE_CONFIG/g" $PANDORA_AGENT_CONF
[[ $PANDORA_GROUP ]] && sed -i "s/^group.*$/group $PANDORA_GROUP/g" $PANDORA_AGENT_CONF
[[ $PANDORA_DEBUG ]] && sed -i "s/^debug.*$/debug $PANDORA_DEBUG/g" $PANDORA_AGENT_CONF
[[ $PANDORA_AGENT_NAME ]] && sed -i "s/^#agent_name.*$/agent_name $PANDORA_AGENT_NAME/g" $PANDORA_AGENT_CONF
[[ $PANDORA_AGENT_ALIAS ]] && sed -i "s/^#agent_alias.*$/agent_alias $PANDORA_AGENT_ALIAS/g" $PANDORA_AGENT_CONF
[[ $PANDORA_SECONDARY_GROUPS ]] && sed -i "s/^# secondary_groups.*$/secondary_groups $PANDORA_SECONDARY_GROUPS/g" $PANDORA_AGENT_CONF
[[ $TIMEZONE ]] && ln -sfn /usr/share/zoneinfo/$TIMEZONE /etc/localtime
[[ $PANDORA_AGENT_SSL ]] && sed -i "s/^#server_ssl.*$/server_ssl $PANDORA_AGENT_SSL/g" $PANDORA_AGENT_CONF

# Verify the configuration was actually applied: the agent could still have
# overwritten the conf after the sed, and the script must not report success
# while sending data to a server the conf does not point to.
conf_server_ip=$(sed -n 's/^server_ip[[:space:]][[:space:]]*//p' "$PANDORA_AGENT_CONF" | head -n 1)
if [ "$PANDORA_SERVER_IP" ] && [ "$conf_server_ip" != "$PANDORA_SERVER_IP" ]; then
    echo -e "${red}Error: server_ip in $PANDORA_AGENT_CONF is '${conf_server_ip:-<none>}', expected '${PANDORA_SERVER_IP}'.${reset}"
    echo "Error installing Pandora FMS Agent for detailed error please check log: $LOGFILE"
    exit 1
fi

#fix systemctl for docker env
if ! systemctl status &>> $LOGFILE ; then
    execute_cmd 'echo compatibility for docker evn' 'The system is not systemd capable, maybe docker env? adding compatibility layer to start /etc/init.d/pandora_agent_daemon'
    mkdir -p /etc/init.d &>> $LOGFILE
    cp /usr/share/pandora_agent/pandora_agent_daemon /etc/init.d/ &>> $LOGFILE
    /etc/init.d/pandora_agent_daemon restart &>> $LOGFILE
else
    # Ensure the service is enabled (idempotent).
    if [ -f /etc/systemd/system/pandora_agent_daemon.service ]; then
        systemctl enable pandora_agent_daemon &>> $LOGFILE
    fi
    # Starting pandora agent daemon.
    systemctl restart pandora_agent_daemon &>> $LOGFILE
fi
echo -en "${cyan}Starting pandora agent... ${reset}"
for _ in {1..5}; do sleep 1 ; ps -aux | grep -v grep | grep -q /usr/bin/pandora_agent ; [[ $? -eq 0 ]] && break ; done
check_cmd_status 'Error cant start pandora agent automatically try to run systemctl restart pandora_agent_daemon manually'
#clean up
cd
execute_cmd 'rm -rf $HOME/pandora_deploy_tmp' 'Cleaning up temporay files'
#Done
echo -e "${green}PandoraFMS Agent installed and running, sending data to: ${conf_server_ip:-$PANDORA_SERVER_IP}${reset}"

