#!/bin/bash
# ╔═══════════════════════════════════════════════════════════════╗
# ║  ScannerSend Installer — CryptoAnnihilator Setup             ║
# ║  https://scannersend.org | ScannerSend Team | MIT License          ║
# ╚═══════════════════════════════════════════════════════════════╝
set -e

GREEN='\033[0;32m'
CYAN='\033[0;36m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
BOLD='\033[1m'
NC='\033[0m'

INSTALL_DIR="/usr/local/bin"
SERVICE_DIR="/etc/systemd/system"
TOOL_URL="https://scannersend.org/download/crypto_annihilator.py"
TOOL_NAME="crypto_annihilator"
VERSION="1.0.0"

echo -e "${CYAN}"
echo '  ╔═══════════════════════════════════════════╗'
echo '  ║     ScannerSend — CryptoAnnihilator       ║'
echo '  ║     Behavioral Crypto Mining Defense       ║'
echo "  ║     v${VERSION}                                ║"
echo '  ╚═══════════════════════════════════════════╝'
echo -e "${NC}"

# ── Check root ──────────────────────────────────────────────
if [ "$(id -u)" -ne 0 ]; then
    echo -e "${RED}Error: Please run as root (sudo)${NC}"
    echo "  curl -sS https://scannersend.org/install.sh | sudo bash"
    exit 1
fi

# ── Check/Install Python 3 ──────────────────────────────────
echo -e "${BOLD}[1/5]${NC} Checking Python 3..."
if command -v python3 &>/dev/null; then
    PY_VER=$(python3 --version 2>&1 | awk '{print $2}')
    echo -e "  ${GREEN}✓${NC} Python ${PY_VER} found"
else
    echo -e "  ${YELLOW}⚠${NC} Python 3 not found. Installing..."
    if command -v apt-get &>/dev/null; then
        apt-get update -qq && apt-get install -y -qq python3 >/dev/null 2>&1
    elif command -v dnf &>/dev/null; then
        dnf install -y -q python3 >/dev/null 2>&1
    elif command -v yum &>/dev/null; then
        yum install -y -q python3 >/dev/null 2>&1
    elif command -v apk &>/dev/null; then
        apk add --quiet python3 >/dev/null 2>&1
    elif command -v pacman &>/dev/null; then
        pacman -Sy --noconfirm python >/dev/null 2>&1
    elif command -v zypper &>/dev/null; then
        zypper install -y python3 >/dev/null 2>&1
    else
        echo -e "${RED}Error: Could not install Python 3. Please install it manually.${NC}"
        exit 1
    fi
    if command -v python3 &>/dev/null; then
        echo -e "  ${GREEN}✓${NC} Python 3 installed"
    else
        echo -e "${RED}Error: Python 3 installation failed.${NC}"
        exit 1
    fi
fi

# ── Verify Python version ≥ 3.6 ────────────────────────────
PY_MIN=$(python3 -c 'import sys; print(1 if sys.version_info >= (3,6) else 0)' 2>/dev/null || echo 0)
if [ "$PY_MIN" != "1" ]; then
    echo -e "${RED}Error: Python 3.6+ required. Found: $(python3 --version 2>&1)${NC}"
    exit 1
fi

# ── Download CryptoAnnihilator ──────────────────────────────
echo -e "${BOLD}[2/5]${NC} Downloading CryptoAnnihilator..."
if command -v curl &>/dev/null; then
    curl -sS -o "${INSTALL_DIR}/${TOOL_NAME}.py" "${TOOL_URL}"
elif command -v wget &>/dev/null; then
    wget -q -O "${INSTALL_DIR}/${TOOL_NAME}.py" "${TOOL_URL}"
else
    echo -e "${RED}Error: Neither curl nor wget found.${NC}"
    exit 1
fi
chmod +x "${INSTALL_DIR}/${TOOL_NAME}.py"

# Create a short alias command
cat > "${INSTALL_DIR}/scannersend" << 'WRAPPER'
#!/bin/bash
exec python3 /usr/local/bin/crypto_annihilator.py "$@"
WRAPPER
chmod +x "${INSTALL_DIR}/scannersend"

LINES=$(wc -l < "${INSTALL_DIR}/${TOOL_NAME}.py")
echo -e "  ${GREEN}✓${NC} Installed to ${INSTALL_DIR}/${TOOL_NAME}.py (${LINES} lines)"
echo -e "  ${GREEN}✓${NC} Command alias: ${BOLD}scannersend${NC}"

# ── Install systemd service (optional) ──────────────────────
echo -e "${BOLD}[3/5]${NC} Setting up systemd service..."
if command -v systemctl &>/dev/null; then
    cat > "${SERVICE_DIR}/scannersend.service" << SVCEOF
[Unit]
Description=ScannerSend — CryptoAnnihilator Daemon
After=network.target
Documentation=https://scannersend.org/docs

[Service]
Type=simple
ExecStart=/usr/bin/python3 ${INSTALL_DIR}/${TOOL_NAME}.py --kill --daemon --interval 30
Restart=always
RestartSec=5
StandardOutput=journal
StandardError=journal
SyslogIdentifier=scannersend

# Security hardening
NoNewPrivileges=false
ProtectSystem=strict
ReadWritePaths=/var/log /var/run /etc/hosts
PrivateTmp=true

[Install]
WantedBy=multi-user.target
SVCEOF
    systemctl daemon-reload
    echo -e "  ${GREEN}✓${NC} Service installed: scannersend.service"
    systemctl enable scannersend &>/dev/null
    systemctl start scannersend &>/dev/null
    echo -e "  ${GREEN}✓${NC} Service started and enabled (running now)"

    # ── Anti-tamper: Make binary and service immutable ──
    if command -v chattr &>/dev/null; then
        chattr +i "${INSTALL_DIR}/${TOOL_NAME}.py" 2>/dev/null
        chattr +i "${SERVICE_DIR}/scannersend.service" 2>/dev/null
        echo -e "  ${GREEN}✓${NC} Anti-tamper: binary and service marked immutable (chattr +i)"
        echo -e "  ${DIM}   To update, run: chattr -i /usr/local/bin/crypto_annihilator.py${NC}"
    fi

    # ── Watchdog: cron-based resurrector ──
    CRON_LINE="* * * * * /usr/bin/systemctl is-active --quiet scannersend || /usr/bin/systemctl start scannersend 2>/dev/null"
    (crontab -l 2>/dev/null | grep -v scannersend; echo "$CRON_LINE") | crontab -
    echo -e "  ${GREEN}✓${NC} Watchdog cron: restarts service if killed (checks every 60s)"

    # ── Boot persistence: also add to rc.local as backup ──
    if [ ! -f /etc/rc.local ] || ! grep -q scannersend /etc/rc.local 2>/dev/null; then
        echo "#!/bin/bash" > /etc/rc.local 2>/dev/null
        echo "systemctl start scannersend 2>/dev/null" >> /etc/rc.local 2>/dev/null
        chmod +x /etc/rc.local 2>/dev/null
        echo -e "  ${GREEN}✓${NC} Boot backup: rc.local fallback"
    fi
else
    # ── No systemd: install cron-based daemon ──
    CRON_LINE="* * * * * pgrep -f crypto_annihilator || /usr/bin/python3 ${INSTALL_DIR}/${TOOL_NAME}.py --kill --daemon --interval 30 >> /var/log/crypto_annihilator/daemon.log 2>&1 &"
    (crontab -l 2>/dev/null | grep -v crypto_annihilator; echo "$CRON_LINE") | crontab -
    echo -e "  ${YELLOW}⚠${NC} systemd not found — installed cron-based daemon (checks every 60s)"
fi

# ── Install firewall rules ──────────────────────────────────
echo -e "${BOLD}[4/5]${NC} Installing network protection..."
python3 "${INSTALL_DIR}/${TOOL_NAME}.py" --install-firewall 2>/dev/null && \
    echo -e "  ${GREEN}✓${NC} Stratum protocol blocked at kernel level" || \
    echo -e "  ${YELLOW}⚠${NC} Firewall rules skipped (iptables not available)"

python3 "${INSTALL_DIR}/${TOOL_NAME}.py" --install-dns-block 2>/dev/null && \
    echo -e "  ${GREEN}✓${NC} Mining pool DNS poisoned" || \
    echo -e "  ${YELLOW}⚠${NC} DNS block skipped"

# ── First scan ──────────────────────────────────────────────
echo -e "${BOLD}[5/5]${NC} Running first scan..."
echo ""
python3 "${INSTALL_DIR}/${TOOL_NAME}.py" --cpu-window 3
RESULT=$?

echo ""
echo -e "${CYAN}══════════════════════════════════════════════${NC}"
if [ $RESULT -eq 0 ]; then
    echo -e "  ${GREEN}✓ System clean. No crypto miners detected.${NC}"
else
    echo -e "  ${RED}⚠ Miners detected! Run with --kill to terminate them.${NC}"
    echo -e "  ${BOLD}  sudo scannersend --kill${NC}"
fi
echo ""
echo -e "  ${BOLD}Commands:${NC}"
echo -e "    ${CYAN}scannersend${NC}              Scan once (dry run)"
echo -e "    ${CYAN}scannersend --kill${NC}       Scan and kill miners"
echo -e "    ${CYAN}scannersend --kill --daemon${NC}  Continuous protection"
echo -e "    ${CYAN}scannersend --status${NC}     Protection status"
echo -e "    ${CYAN}scannersend --uninstall${NC}  Clean removal (all layers)"
echo -e "    ${CYAN}systemctl start scannersend${NC}  Run as background service"
echo ""
echo -e "  ${BOLD}Docs:${NC} https://scannersend.org/docs"
echo -e "  ${BOLD}Source:${NC} https://scannersend.org/source"
echo -e "${CYAN}══════════════════════════════════════════════${NC}"
echo -e "  ${GREEN}ScannerSend v${VERSION} — ScannerSend Team${NC}"
echo -e "  ${GREEN}It scans for crypto miners. It sends them to oblivion.${NC}"
echo ""
