#!/bin/bash

# DNSBlock Agent Installer

INSTALL_DIR="/opt/dnsblock"
SOURCE_DIR=$(pwd)

# Check root using id -u (compatible with sh/dash)
if [ "$(id -u)" -ne 0 ]; then
  echo "Please run as root"
  exit 1
fi

echo "Installing DNSBlock Agent..."

# Check for Python 3
if ! command -v python3 &> /dev/null; then
    echo "Error: python3 is not installed."
    exit 1
fi

# Try to install python3-venv and python3-pip if apt is available
if command -v apt-get &> /dev/null; then
    echo "Checking system dependencies..."
    apt-get update
    apt-get install -y python3-venv python3-pip
fi

# Create Directory
mkdir -p "$INSTALL_DIR"

# Copy Files
cp "$SOURCE_DIR/main.py" "$INSTALL_DIR/"
cp "$SOURCE_DIR/requirements.txt" "$INSTALL_DIR/"

# Setup Virtual Environment
if [ ! -d "$INSTALL_DIR/venv" ] || [ ! -f "$INSTALL_DIR/venv/bin/pip" ]; then
    echo "Creating virtual environment..."
    python3 -m venv "$INSTALL_DIR/venv"
    
    if [ $? -ne 0 ] || [ ! -f "$INSTALL_DIR/venv/bin/pip" ]; then
        echo "Error: Failed to create virtual environment."
        echo "Please ensure python3-venv is installed (e.g., apt install python3-venv)"
        exit 1
    fi
fi

# Install Dependencies
echo "Installing dependencies..."
"$INSTALL_DIR/venv/bin/pip" install -r "$INSTALL_DIR/requirements.txt"

# Create Config if not exists
if [ ! -f "$INSTALL_DIR/config.json" ]; then
    echo "Creating default config..."
    cat <<EOF > "$INSTALL_DIR/config.json"
{
    "serial_key": "YOUR_SERIAL_KEY_HERE",
    "api_url": "https://seu-painel.com",
    "rpz_file": "/opt/dnsblock/rpz.dnsblock.zone"
}
EOF
    echo "Config file created at $INSTALL_DIR/config.json. Please edit it with your Serial Key and API URL."
fi

# Setup Systemd Service
echo "Setting up systemd service..."
cp "$SOURCE_DIR/dnsblock-agent.service" /etc/systemd/system/
systemctl daemon-reload
systemctl enable dnsblock-agent

echo "Installation Complete!"
echo "1. Edit /opt/dnsblock/config.json"
echo "2. Start service: systemctl start dnsblock-agent"
