#!/usr/bin/env bash
# ==============================================================================
# TG AUTO REPLY PRO - LINUX SYSTEM AUTOMATIC INSTALLER
# ==============================================================================

# Exit immediately if a command exits with a non-zero status
set -e

echo "======================================================================"
echo "          TG Auto Reply Pro - Linux Setup Installer Script             "
echo "======================================================================"

# Determine Package Manager and OS
if [ -f /etc/debian_version ]; then
    OS="debian"
    PM="apt-get"
elif [ -f /etc/redhat-release ] || [ -f /etc/system-release ]; then
    OS="redhat"
    PM="dnf"
else
    echo "[!] OS distribution not officially recognized. Attempting default installations..."
    OS="unknown"
    PM="apt-get"
fi

echo "[*] Detected OS Type: $OS ($PM)"
echo "[*] Updating system repositories and installing dependencies..."

if [ "$PM" = "apt-get" ]; then
    sudo apt-get update -y
    sudo apt-get install -y python3 python3-pip python3-venv python3-dev sqlite3 build-essential libffi-dev libssl-dev
elif [ "$PM" = "dnf" ]; then
    sudo dnf check-update || true
    sudo dnf install -y python3 python3-pip python3-devel sqlite gcc openssl-devel libffi-devel
fi

# Create Directories
echo "[*] Creating required folder directories..."
mkdir -p config database logs sessions templates static modules

# Setup Virtual Environment
echo "[*] Creating Python Virtual Environment (venv)..."
python3 -m venv venv

# Activate and Install Requirements
echo "[*] Activating virtual environment and installing packages..."
source venv/bin/activate
pip install --upgrade pip
pip install -r requirements.txt

# Finish Info
echo "======================================================================"
echo "[+] TG Auto Reply Pro environment successfully initialized!"
echo "======================================================================"
echo "To start the application daemon, execute:"
echo "    source venv/bin/activate"
echo "    python main.py"
echo ""
echo "Or run the startup wrapper:"
echo "    chmod +x start.sh"
echo "    ./start.sh"
echo "======================================================================"
