#!/bin/bash
INSTALL="no"
UNINSTALL="no"
CREATE_USER="yes"
PRC_KEY=""
EH_USER=""
TMP_DIR=""
INSTALL_DIR="/usr/bin"
CONF_DIR="/etc/pandorarc"
OLD_CONF_DIR="/etc/ehorus"
NEW_SHARE_DIR="/usr/share/pandorarc"
OLD_SHARE_DIR="/usr/share/ehorus"
SERVICE_DIR="/etc/systemd/system"
OS_NAME=`uname -s`
ARCH=`uname -m`

# Darwin check
if [ "$OS_NAME" == "Darwin" ]; then
    echo "This installer is not compatible with MacOS systems. Please use the Darwin-based installer instead."
    echo "Exiting..."
    exit 1
fi

if [ "$ARCH" == "aarch64" ] || [[ "$ARCH" =~ (arm) ]]; then
    echo "This installer is not compatible with ARM systems. Please use the raspberry installer instead."
    echo "Exiting..."
    exit 1
fi

if [ "$OS_NAME" == "Linux" ]; then
    DISTRO=$(grep ^PRETTY_NAME= /etc/os-release | cut -d '=' -f2 | tr -d '"')
    if [[ "${DISTRO,,}" =~ (centos|alma|red hat|rocky) ]]; then
        RHEL_VERSION=$(echo "$DISTRO" | grep -oP "(?<=\s)[0-9]*")

        if [ "$RHEL_VERSION" -lt "7" ]; then
            echo "This installer is only compatible with el7 systems and above."
            echo "Exiting..."
            exit 1
        fi
    fi
else
    DISTRO="UNSUPPORTED"
fi

echo "Pandora RC Agent installer for $DISTRO. (c) 2015-2026 Pandora FMS."
echo

# Extra options parsing
while [ "$1" != "" ]; do
    case "$1" in
        --install)
            INSTALL="yes"
            ;;
        --uninstall)
            UNINSTALL="yes"
            ;;
        --prc_key)
            PRC_KEY=$2
            shift
            ;;
        --prc_user)
            EH_USER=$2
            shift
            ;;
        --no_user)
            CREATE_USER="no"
            ;;
        --tmp_dir)
            TMP_DIR=$2
            shift
            ;;
    esac
    shift
done

ALREADY_INSTALLED="0"

# Install logic
if [ "$INSTALL" == "yes" ]
then
    # 1. PROCESS CLEANUP (Critical for Display/VNC functionality)
    echo "> Stopping all legacy and current processes..."
    
    # Kill legacy ehorus processes
    pkill -9 -f "ehorus" 2>/dev/null
    
    PIDS_TO_KILL=$(ps -ef | grep "pandorarc" | grep -v -E "grep|installer|$$" | awk '{print $2}')

    if [ -n "$PIDS_TO_KILL" ]; then
        kill -9 $PIDS_TO_KILL 2>/dev/null || true
    fi

    systemctl stop ehorus_agent_daemon pandorarc_agent_daemon 2>/dev/null
    sync && sleep 1

    # 2. TEMPORARY FILES PURGE (Hex codes for root, pandorarc, and ehorus)
    echo "> Cleaning temporary sockets and locks..."
    rm -rf /tmp/par-726f6f74 /tmp/par-70616e646f72617263 /tmp/par-65686f727573 2>/dev/null
    rm -f /tmp/.X11-unix/X* /tmp/.X*-lock 2>/dev/null 

    if [ -n "$RHEL_VERSION" ] && [ "$RHEL_VERSION" -ge "8" ]; then
        ldconfig -p | grep "libnsl\.so\.1" 2>&1 > /dev/null
        if [ $? != "0" ]; then
            echo "The dependency 'libnsl' was not found. Please install it and try again."
            echo "Aborting..."
            exit 1
        fi
    fi

    # 3. USER & DIRECTORY CREATION (Ensures a valid Home for the Display engine)
    if [ "$CREATE_USER" == "yes" ]
    then
        echo "Checking Pandora RC user"
        mkdir -p "$NEW_SHARE_DIR" # Guaranteed directory creation
        id pandorarc 2> /dev/null
        if [ $? -eq 0 ]; then
            echo " "
            echo "User 'pandorarc' does exist, ensuring homedir is $NEW_SHARE_DIR"
            usermod -d "$NEW_SHARE_DIR" pandorarc 2>/dev/null
        else
            echo "Are you sure we can create a standard 'pandorarc' user locally? [y/N]"
            if [ -t 0 ]; then read AREYOUSURE; else AREYOUSURE="y"; fi

            if [ "$AREYOUSURE" = "y" ]; then
                /usr/sbin/useradd -d "$NEW_SHARE_DIR" -p MsYr4zch5PQ42 -s /sbin/nologin pandorarc 
            else
                echo "Please create the user manually and restart. Aborting..."
                exit 1
            fi
        fi
        chown -R pandorarc:pandorarc "$NEW_SHARE_DIR"
        chmod 750 "$NEW_SHARE_DIR"
    fi

    echo
    echo "> Installing the Pandora RC agent to $INSTALL_DIR..."
    if [ -f "$INSTALL_DIR/pandorarc_agent" ]
    then
        VERSION_CMP=`$INSTALL_DIR/pandorarc_agent -c 201`
        if [ "$VERSION_CMP" -eq "1" ] 
        then
            echo "[EXIT] There is a newer version already installed"
            exit 0
        else
            echo "> An older version will be overwritten"
        fi
        ALREADY_INSTALLED="1"
    fi

    cp -f pandorarc_agent "$INSTALL_DIR"/pandorarc_agent || exit 2
    rm -f "$INSTALL_DIR/ehorus_agent" 2>/dev/null

    echo "> Copying configuration file to $CONF_DIR..."
    mkdir -p "$CONF_DIR" 2>/dev/null || exit 3

    # Log rotation
    if [ -d /etc/logrotate.d ] &&  [ ! -f /etc/logrotate.d/pandorarc_agent.conf ]
    then
        echo "> Adding logrotate configuration file..."
        cp pandorarc_agent_logrotate /etc/logrotate.d/pandorarc_agent.conf
    fi
    rm -f /etc/logrotate.d/ehorus_agent.conf 2>/dev/null

    # TMP_DIR to service file
    [ -n "$TMP_DIR" ] && mkdir -p "$TMP_DIR" && sed -i "/\[Service\]/a Environment=\"PAR_GLOBAL_TMPDIR=$TMP_DIR\"" pandorarc_agent_daemon.service

    # LEGACY SERVICE CLEANUP
    OLD_SERVICE_NAMES="ehorus_agent_daemon.service pandorarc_agent_daemon.service"
    SERVICE_PATHS="/etc/systemd/system /usr/lib/systemd/system /lib/systemd/system"
    for NAME in $OLD_SERVICE_NAMES; do
        for S_PATH in $SERVICE_PATHS; do
            if [ -f "$S_PATH/$NAME" ]; then
                systemctl disable "$NAME" 2>/dev/null
                rm -f "$S_PATH/$NAME"
            fi
        done
    done
    rm -f /etc/init.d/ehorus_agent_daemon 2>/dev/null
    systemctl daemon-reload

    # MIGRATION BLOCK
    OLD_CONF_FILE="$OLD_CONF_DIR/ehorus_agent.conf"
    NEW_CONF_FILE="$CONF_DIR/pandorarc_agent.conf"

    if [ -f "$OLD_CONF_FILE" ]; then
        echo "> Old configuration found. Migrating data and rebranding..."
        if [ -d "$OLD_SHARE_DIR" ]; then
            cp -rp "$OLD_SHARE_DIR/." "$NEW_SHARE_DIR/" 2>/dev/null
            rm -rf "$OLD_SHARE_DIR"
            chown -R pandorarc:pandorarc "$NEW_SHARE_DIR"
        fi
        sed -e "s/eh_/prc_/g" -e "s/ehorus/pandorarc/g" "$OLD_CONF_FILE" > "$NEW_CONF_FILE"
        rm -rf "$OLD_CONF_DIR"
        NEW_CONF="1"
    else
        cp -f pandorarc_agent.conf "$NEW_CONF_FILE"
        NEW_CONF="0"
    fi

    # Set configuration parameters
    [ -n "$PRC_KEY" ] && sed -i -e "s/.*prc_key.*/prc_key $PRC_KEY/" "$NEW_CONF_FILE"
    [ -n "$EH_USER" ] && sed -i -e "s/.*prc_user.*/prc_user $EH_USER/" "$NEW_CONF_FILE"

    echo "> Copying licenses file..."
    cp -f LICENSES.README "$CONF_DIR"
    
    # Systemd registration
    if [ "$2" != "--disabled" ]
    then
        echo "> Creating systemd service..."
        cp -f pandorarc_agent_daemon.service "$SERVICE_DIR/pandorarc_agent_daemon.service" || exit 5
        systemctl daemon-reload
        systemctl enable pandorarc_agent_daemon.service 2>/dev/null
    fi
    
    echo
    if [ "$EH_USER" ] && [ "$NEW_CONF" -eq "1" ]; then
        echo "The user $EH_USER has been configured in $CONF_DIR/pandorarc_agent.conf file."
    else
        echo "Edit the file $CONF_DIR/pandorarc_agent.conf and set prc_user before starting."
    fi
    echo
    if [ "$ALREADY_INSTALLED" -eq "1" ]; then
        echo "Restart the agent to apply the update."
        echo
    fi

# Uninstall logic
elif [ "$UNINSTALL" == "yes" ]
then
    PROV=$(grep "prov_address" "$CONF_DIR/pandorarc_agent.conf" 2>/dev/null | cut -d ' ' -f2)
    [ -n "$PROV" ] && echo "Unregistering Agent from $PROV..." && "$INSTALL_DIR/pandorarc_agent" -f "$CONF_DIR/pandorarc_agent.conf" -r >/dev/null 2>&1
    
    rm -rf /tmp/par-726f6f74 /tmp/par-70616e646f72617263 /tmp/par-65686f727573 2>/dev/null

    echo "> Uninstalling the Pandora RC Agent..."
    rm -f "$INSTALL_DIR/pandorarc_agent"
    rm -rf "$CONF_DIR"
    rm -f "/etc/logrotate.d/pandorarc_agent.conf"
    
    if [ -f "$SERVICE_DIR/pandorarc_agent_daemon.service" ]
    then
        systemctl stop pandorarc_agent_daemon.service 2>/dev/null
        rm -f "$SERVICE_DIR/pandorarc_agent_daemon.service"
        systemctl daemon-reload
    fi
    
    id pandorarc 2> /dev/null && echo "User 'pandorarc' detected. Use 'userdel pandorarc' if needed."

else
    echo "Usage: $0 [--install|--uninstall] [--prc_user USER] [--prc_key KEY] [--disabled]"
    echo "  --install   To install Pandora RC agent on this system (you must be root)"
    echo "  --uninstall To uninstall and remove Pandora RC agent on this System"
    echo " "
    echo " Optional parameters:"
    echo " "
    echo " --prc_user   PRC_USER to manually set the prc_user on Pandora RC agent"
    echo " --prc_key    PRC_KEY to manually set a prc_key on Pandora RC agent"
    echo " --no_user    use it to prevent the creation of the 'pandorarc' system user"
    echo " --tmp_dir    TMP_DIR to manually set a custom TMP directory for the agent (for noexec cases)"
    echo " --disabled   prevents pandorarc_agent_daemon service from being added to systemd"
fi
