#!/bin/bash

echo "Starting CSF installation process..."

# Step 1: Install dependencies
echo "Checking and installing required Perl modules..."
REQUIRED_PACKAGES=(
  perl-libwww-perl.noarch
  perl-LWP-Protocol-https.noarch
  perl-GDGraph
)

for pkg in "${REQUIRED_PACKAGES[@]}"; do
  if rpm -q "$pkg" &>/dev/null; then
    echo "$pkg is already installed."
  else
    echo "$pkg is not installed. Installing..."
    dnf install -y "$pkg"
  fi
done

# Step 2: Change to /usr/src and download CSF
cd /usr/src || exit 1

echo "Attempting to download CSF from official URL..."
if ! wget https://scripts.sabinserver.com/csf.tgz; then
  echo "Primary download failed, trying backup IP..."
  if ! wget https://94.130.90.175/csf.tgz; then
    echo "Both download attempts failed. Exiting."
    exit 1
  fi
fi

# Step 3: Extract and install
echo "Extracting CSF package..."
tar -xzf csf.tgz
cd csf || exit 1
echo "Installing CSF..."
sh install.sh

echo "Installation complete."

# Step 4: Test CSF
echo "Running CSF test script..."
perl /usr/local/csf/bin/csftest.pl

# Step 5: Disable firewalld
echo "Disabling and stopping firewalld..."
systemctl stop firewalld
systemctl disable firewalld

# Step 6: Update csf.conf
CONFIG_FILE="/etc/csf/csf.conf"
if [ -f "$CONFIG_FILE" ]; then
  echo "Updating csf.conf settings..."
  sed -i 's/^TESTING = "1"/TESTING = "0"/' "$CONFIG_FILE"
  sed -i 's/^RESTRICT_SYSLOG = "0"/RESTRICT_SYSLOG = "3"/' "$CONFIG_FILE"
else
  echo "Error: csf.conf not found!"
  exit 1
fi

# Step 7: Start CSF and LFD
echo "Starting and enabling CSF and LFD services..."
systemctl start csf
systemctl start lfd
systemctl enable csf
systemctl enable lfd

# Step 8: Restart CSF
csf -r

echo -e "\n✅ Thanks for using SabinServer! Installation complete."
