#!/bin/bash
# GRSG Office Cloud Print Agent - Linux/Mac Installer
# ====================================================

echo ""
echo "=========================================="
echo " GRSG Office Cloud Print Agent Installer"
echo "=========================================="
echo ""

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
SUDO=""
if [ "$EUID" -ne 0 ] && command -v sudo &> /dev/null; then
    SUDO="sudo"
fi

# Check Python
PYTHON_EXE=""
if command -v python3.11 &> /dev/null; then
    PYTHON_EXE=$(command -v python3.11)
elif command -v python3.10 &> /dev/null; then
    PYTHON_EXE=$(command -v python3.10)
elif command -v python3 &> /dev/null; then
    PYTHON_EXE=$(command -v python3)
else
    echo "ERROR: Python 3 is not installed!"
    echo "Please install Python 3:"
    echo "  Ubuntu/Debian: sudo apt install python3 python3-pip"
    echo "  macOS: brew install python3"
    exit 1
fi

PY_VER=$($PYTHON_EXE -c "import sys; print(f'{sys.version_info[0]}.{sys.version_info[1]}')")
if [ "$PY_VER" = "3.12" ]; then
    echo "ERROR: Python 3.12 is not supported with pysnmp<7 (asyncore removed)."
    echo "Install Python 3.11 or 3.10 and re-run this installer."
    echo "Ubuntu (recommended):"
    echo "  sudo add-apt-repository ppa:deadsnakes/ppa"
    echo "  sudo apt update"
    echo "  sudo apt install python3.11 python3.11-venv"
    exit 1
fi

echo "[1/5] Installing system SNMP tools..."
if command -v snmpget &> /dev/null && command -v snmpwalk &> /dev/null; then
    echo "      SNMP tools already installed."
else
    if command -v apt-get &> /dev/null; then
        $SUDO apt-get update
        $SUDO apt-get install -y snmp
    elif command -v dnf &> /dev/null; then
        $SUDO dnf install -y net-snmp-utils
    elif command -v yum &> /dev/null; then
        $SUDO yum install -y net-snmp-utils
    elif command -v brew &> /dev/null; then
        brew install net-snmp
    else
        echo "WARNING: Could not install SNMP tools automatically."
        echo "Please install snmpget/snmpwalk manually for metrics collection."
    fi
fi
echo "      Done!"
echo ""

echo "[2/5] Installing required packages..."
"$PYTHON_EXE" -m pip install --upgrade pip -q
"$PYTHON_EXE" -m pip install requests "pysnmp<7" -q
echo "      Done!"
echo ""

# Ask for configuration
echo "[3/5] Configuration"
echo "=========================================="
echo ""

read -p "Enter your Agent Token: " AGENT_TOKEN
if [ -z "$AGENT_TOKEN" ]; then
    echo "ERROR: Token is required!"
    exit 1
fi

echo ""
read -p "Enter Cloud URL (e.g., https://yourserver.com): " CLOUD_URL
if [ -z "$CLOUD_URL" ]; then
    echo "ERROR: Cloud URL is required!"
    exit 1
fi

echo ""
read -p "Enter network to scan [192.168.1.0/24]: " NETWORK
NETWORK=${NETWORK:-192.168.1.0/24}

# Save config
echo ""
echo "[4/5] Saving configuration..."
cat > "$SCRIPT_DIR/agent_config.json" << EOF
{
  "token": "$AGENT_TOKEN",
  "cloud_url": "$CLOUD_URL",
  "network": "$NETWORK",
  "sync_interval": 300
}
EOF
echo "      Done!"

echo ""
echo "[5/5] Creating background runner..."
cat > "$SCRIPT_DIR/run_agent.sh" << 'EOF'
#!/bin/bash
set -e
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
CONFIG_PATH="$SCRIPT_DIR/agent_config.json"
if [ ! -f "$CONFIG_PATH" ]; then
    echo "Missing config: $CONFIG_PATH"
    exit 1
fi

PYTHON_EXE=""
if command -v python3.11 &> /dev/null; then
    PYTHON_EXE=$(command -v python3.11)
elif command -v python3.10 &> /dev/null; then
    PYTHON_EXE=$(command -v python3.10)
else
    PYTHON_EXE=$(command -v python3)
fi

"$PYTHON_EXE" -c "import pysnmp" >/dev/null 2>&1 || "$PYTHON_EXE" -m pip install "pysnmp<7" -q

while true; do
    "$PYTHON_EXE" "$SCRIPT_DIR/grgs_office_agent.py"
    sleep 10
done
EOF
chmod +x "$SCRIPT_DIR/run_agent.sh"
echo "      Done!"

echo ""
echo "=========================================="
echo " Installation Complete!"
echo "=========================================="
echo ""
echo "Config saved to: $SCRIPT_DIR/agent_config.json"
echo "Auto-run script: $SCRIPT_DIR/run_agent.sh"
echo ""

# Automatically start agent in background
echo "Starting agent in background..."
nohup "$SCRIPT_DIR/run_agent.sh" > "$SCRIPT_DIR/agent.log" 2>&1 &
echo "Agent started. Log: $SCRIPT_DIR/agent.log"

# Add startup entry to crontab for agent user
CRON_CMD="$SCRIPT_DIR/run_agent.sh > $SCRIPT_DIR/agent.log 2>&1 &"
CRON_ENTRY="@reboot $CRON_CMD"
CRON_EXISTS=$(sudo crontab -u $SERVICE_USER -l 2>/dev/null | grep -F "$CRON_CMD" || true)
if [ -z "$CRON_EXISTS" ]; then
    (sudo crontab -u $SERVICE_USER -l 2>/dev/null; echo "$CRON_ENTRY") | sudo crontab -u $SERVICE_USER -
    echo "Startup entry added to crontab for $SERVICE_USER."
else
    echo "Startup entry already exists in crontab for $SERVICE_USER."
fi

# Automatically install and start systemd service
SERVICE_PATH="/etc/systemd/system/grgs_office_agent.service"
SERVICE_USER="$(id -un)"
$SUDO tee "$SERVICE_PATH" > /dev/null << EOF
[Unit]
Description=GRSG Office Cloud Print Agent
After=network.target

[Service]
Type=simple
User=$SERVICE_USER
WorkingDirectory=$SCRIPT_DIR
ExecStart=$SCRIPT_DIR/run_agent.sh
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target
EOF
$SUDO systemctl daemon-reload
$SUDO systemctl enable grgs_office_agent
$SUDO systemctl restart grgs_office_agent
echo "Service installed and started."
