#!/bin/bash

# Ensure the script is run as root
[ "$(id -u)" -ne 0 ] && echo "ERR: must be run as: root" && exit 1

# Detect the operating system
OS=$(cat /etc/*release | grep -i "centos\|debian" | head -n 1 | awk -F= '{print $2}' | tr -d '[:space:]')

if [[ "$OS" =~ "CentOS" ]]; then
    PACKAGE_MANAGER="dnf"
    REPO_INSTALL_CMD="dnf install"
    PHP_INSTALL_CMD="dnf module install php:remi-8.3 -y"
elif [[ "$OS" =~ "Debian" ]]; then
    PACKAGE_MANAGER="apt"
    REPO_INSTALL_CMD="apt-get install"
    PHP_INSTALL_CMD="apt-get install php php-cli php-fpm php-pgsql php-yaml php-pdo -y"
else
    echo "ERR: Unsupported OS, must be CentOS or Debian."
    exit 1
fi

# Install necessary repositories for CentOS or Debian
if [[ "$OS" =~ "CentOS" ]]; then
    $REPO_INSTALL_CMD https://dl.fedoraproject.org/pub/epel/epel-release-latest-9.noarch.rpm -y
    $REPO_INSTALL_CMD https://rpms.remirepo.net/enterprise/remi-release-9.rpm -y
    $PHP_INSTALL_CMD
elif [[ "$OS" =~ "Debian" ]]; then
    $REPO_INSTALL_CMD lsb-release wget curl -y
    # PHP installation is already included in the above command
fi

# Install required packages (PostgreSQL, Apache, PHP, and utilities)
$REPO_INSTALL_CMD net-tools postgresql postgresql-server httpd php-fpm -y
$REPO_INSTALL_CMD php-pecl-yaml php-pgsql php-pdo -y

# Setup PostgreSQL
if [[ "$OS" =~ "CentOS" ]]; then
    /usr/bin/postgresql-setup --initdb
    systemctl enable postgresql
    systemctl start postgresql
elif [[ "$OS" =~ "Debian" ]]; then
    service postgresql start
fi

# Configure PostgreSQL to allow external connections securely
cd /var/lib/pgsql/data || exit
cp pg_hba.conf pg_hba.conf.backup

# Allow connections from any IP (recommended to restrict IP range later)
sed -i 's|host    all             all             127.0.0.1/32            ident|host    all             all             0.0.0.0/0            md5|g' pg_hba.conf

# Restart PostgreSQL to apply changes
systemctl restart postgresql

# Create the Pandabot database
su - postgres -c 'psql -c "CREATE DATABASE pandabot;"'

# Display configuration instructions
echo -e "\n------------------------- --- -- -  -"
echo "Edit conf/pandabot.conf and conf/channels.conf"
echo "Database settings:"
echo "dbname: pandabot"
echo "dbhost: $(hostname -I | awk '{print $1}')"
echo "dbport: 5432"
echo "dbuser: postgres"
echo "dbpass: <set_your_password_here>"

echo -e "\nTo setup the Telegram session, run: ./bot.sh setuptg"
echo "To start the bot, run: ./bot.sh start"
echo "To stop the bot, run: ./bot.sh stop"
echo -e "------------------------- --- -- -  -\n"

# Check if firewall is enabled and add necessary rules for PostgreSQL and Apache
if systemctl is-active --quiet firewalld; then
    echo "Configuring firewall for PostgreSQL (5432) and HTTP (80/443)"
    firewall-cmd --zone=public --add-port=5432/tcp --permanent
    firewall-cmd --zone=public --add-service=http --permanent
    firewall-cmd --reload
elif ufw status | grep -q "active"; then
    echo "Configuring UFW for PostgreSQL (5432) and HTTP (80/443)"
    ufw allow 5432/tcp
    ufw allow http
    ufw allow https
    ufw reload
fi

# SELinux setup for CentOS (optional step, recommended to allow postgresql and httpd)
if [[ "$OS" =~ "CentOS" ]]; then
    echo "Setting up SELinux to allow PostgreSQL and Apache to work together"
    setsebool -P httpd_can_network_connect_db 1
    setsebool -P httpd_can_network_connect 1
fi

echo "Installation and setup complete."
