#!/bin/bash
# RTExit Native Kali Linux Installer v4.0
# Installs all 300+ tools directly on Kali Linux
# ✅ All install methods verified in live container testing
# ✅ Uses correct binary/apt/pip methods discovered during gap analysis
#
# Usage:
#   chmod +x rt-native-install.sh
#   sudo bash rt-native-install.sh

set -e

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

[ "$EUID" -ne 0 ] && echo -e "${RED}[!] Run as root: sudo bash rt-native-install.sh${NC}" && exit 1

echo -e "${RED}"
cat << 'EOF'
  ██████╗ ████████╗███████╗██╗  ██╗██╗████████╗
  ██╔══██╗╚══██╔══╝██╔════╝╚██╗██╔╝██║╚══██╔══╝
  ██████╔╝   ██║   █████╗   ╚███╔╝ ██║   ██║
  ██╔══██╗   ██║   ██╔══╝   ██╔██╗ ██║   ██║
  ██║  ██║   ██║   ███████╗██╔╝ ██╗██║   ██║
  ╚═╝  ╚═╝   ╚═╝   ╚══════╝╚═╝  ╚═╝╚═╝   ╚═╝
EOF
echo -e "${NC}${BOLD}  Native Kali Installer v4.0 — 300+ Tools (Verified)${NC}"
echo -e "  ${CYAN}All methods tested in live environment${NC}"
echo ""

# ── Helpers ───────────────────────────────────────────────────────────────────
OK=0; FAIL=0

apt_install() {
  echo -e "  ${BLUE}[APT]${NC} $*"
  apt-get install -y --no-install-recommends "$@" 2>/dev/null && OK=$((OK+1)) || FAIL=$((FAIL+1))
}

pip_install() {
  echo -e "  ${BLUE}[PIP]${NC} $*"
  pip3 install --no-cache-dir --break-system-packages "$@" 2>/dev/null && OK=$((OK+1)) || FAIL=$((FAIL+1))
}

# NOTE: checkov requires --ignore-installed (system packaging conflict)
pip_force() {
  echo -e "  ${BLUE}[PIP+]${NC} $*"
  pip3 install --no-cache-dir --break-system-packages --ignore-installed "$@" 2>/dev/null && OK=$((OK+1)) || FAIL=$((FAIL+1))
}

go_install() {
  echo -e "  ${BLUE}[GO ]${NC} $1"
  export PATH="$PATH:/root/go/bin"; export GOPATH=/root/go
  go install "$1" 2>/dev/null && OK=$((OK+1)) || FAIL=$((FAIL+1))
  # Always copy to system PATH so it's accessible without GOPATH
  local bin_name; bin_name=$(basename "${1%@*}" | cut -d/ -f1)
  [ -f "/root/go/bin/$bin_name" ] && cp "/root/go/bin/$bin_name" /usr/local/bin/ 2>/dev/null || true
}

gem_install() {
  echo -e "  ${BLUE}[GEM]${NC} $*"
  gem install "$@" 2>/dev/null && OK=$((OK+1)) || FAIL=$((FAIL+1))
}

npm_install() {
  echo -e "  ${BLUE}[NPM]${NC} $*"
  npm install -g "$@" 2>/dev/null && OK=$((OK+1)) || FAIL=$((FAIL+1))
}

clone() {
  local repo="$1" dest="$2"
  echo -e "  ${BLUE}[GIT]${NC} $dest"
  if [ ! -d "$dest" ]; then
    git clone --depth 1 "$repo" "$dest" -q 2>/dev/null && OK=$((OK+1)) || FAIL=$((FAIL+1))
  else
    echo -e "  ${YELLOW}[SKP]${NC} $dest (already exists)"
    OK=$((OK+1))
  fi
}

binary_download() {
  local name="$1" url="$2" dest="${3:-/usr/local/bin/$1}"
  echo -e "  ${BLUE}[BIN]${NC} $name"
  curl -sL "$url" -o "/tmp/${name}_dl" 2>/dev/null && mv "/tmp/${name}_dl" "$dest" && chmod +x "$dest" && OK=$((OK+1)) || FAIL=$((FAIL+1))
}

section() {
  echo ""
  echo -e "${CYAN}${BOLD}══ $1 ══${NC}"
}

# ── System Update ─────────────────────────────────────────────────────────────
section "System Update"
apt-get update -qq && apt-get upgrade -y -qq

# ── Core Dependencies ─────────────────────────────────────────────────────────
section "Core Dependencies"
apt_install curl wget git vim nano tmux screen \
  file xxd hexedit zip unzip p7zip-full tar jq \
  build-essential python3 python3-pip python3-venv \
  libssl-dev libffi-dev libpcap-dev \
  golang-go nodejs npm default-jdk ruby ruby-dev \
  libgmp-dev libmpfr-dev libmpc-dev

export PATH="$PATH:/root/go/bin"
export GOPATH=/root/go

# ── Aliases (rt-* shortcuts) ──────────────────────────────────────────────────
section "RTExit Aliases"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ALIASES_SRC="$SCRIPT_DIR/../docker/aliases.sh"
if [ -f "$ALIASES_SRC" ]; then
  cp "$ALIASES_SRC" /etc/profile.d/rtexit-aliases.sh
  chmod +x /etc/profile.d/rtexit-aliases.sh
  echo -e "  ${GREEN}✅${NC} rt-* aliases installed"
fi

# ════════════════════════════════════════════════════════════
# PHASE 1 — Scanning & Recon
# ════════════════════════════════════════════════════════════
section "Phase 1 — Scanning & Recon"

# Verified via apt (reliable)
apt_install nmap masscan zmap naabu \
  dnsrecon dnsenum fierce \
  dirb nikto whatweb wafw00f testssl.sh

# rustscan — MUST use deb package (not cargo, too slow)
echo -e "  ${BLUE}[DEB]${NC} rustscan"
curl -sL "https://github.com/RustScan/RustScan/releases/download/2.3.0/rustscan_2.3.0_amd64.deb" \
  -o /tmp/rustscan.deb 2>/dev/null && dpkg -i /tmp/rustscan.deb 2>/dev/null && rm /tmp/rustscan.deb || true

# feroxbuster — binary download (go install is slow, binary is instant)
echo -e "  ${BLUE}[BIN]${NC} feroxbuster"
curl -sL "https://github.com/epi052/feroxbuster/releases/latest/download/x86_64-linux-feroxbuster.zip" \
  -o /tmp/ferox.zip 2>/dev/null && unzip -qo /tmp/ferox.zip -d /usr/local/bin/ feroxbuster && rm /tmp/ferox.zip || true

# x8 — MUST use binary (.gz), NOT go install (module path is broken in go install)
echo -e "  ${BLUE}[BIN]${NC} x8"
curl -sL "https://github.com/Sh1Yo/x8/releases/download/v4.3.0/x86_64-linux-x8.gz" \
  -o /tmp/x8.gz 2>/dev/null && gunzip /tmp/x8.gz && mv /tmp/x8 /usr/local/bin/x8 && chmod +x /usr/local/bin/x8 || true

# pip scanning tools
pip_install dirsearch wfuzz

# Go tools (all copy to /usr/local/bin automatically)
go_install github.com/projectdiscovery/httpx/cmd/httpx@latest
go_install github.com/projectdiscovery/nuclei/v3/cmd/nuclei@latest
go_install github.com/projectdiscovery/subfinder/v2/cmd/subfinder@latest
go_install github.com/projectdiscovery/naabu/v2/cmd/naabu@latest
go_install github.com/projectdiscovery/katana/cmd/katana@latest
go_install github.com/projectdiscovery/dnsx/cmd/dnsx@latest
go_install github.com/hakluke/hakrawler@latest
go_install github.com/tomnomnom/waybackurls@latest
go_install github.com/lc/gau/v2/cmd/gau@latest
go_install github.com/ffuf/ffuf/v2@latest
go_install github.com/OJ/gobuster/v3@latest
go_install github.com/LukaSikic/subzy@latest
go_install github.com/PentestPad/subzy@latest    # fallback — use PentestPad fork
go_install github.com/hahwul/dalfox/v2@latest
go_install github.com/tomnomnom/httprobe@latest
go_install github.com/d3mondev/puredns/v2@latest
go_install github.com/sensepost/gowitness@latest
go_install github.com/LukaSikic/subzy@latest
go_install github.com/projectdiscovery/interactsh/cmd/interactsh-client@latest
go_install github.com/tomnomnom/qsreplace@latest
go_install github.com/Emoe/kxss@latest

# gitleaks — binary download (not pip — pip version is outdated)
echo -e "  ${BLUE}[BIN]${NC} gitleaks"
curl -sSL "https://github.com/gitleaks/gitleaks/releases/download/v8.18.2/gitleaks_8.18.2_linux_x64.tar.gz" \
  -o /tmp/gl.tar.gz 2>/dev/null && tar xf /tmp/gl.tar.gz -C /usr/local/bin gitleaks && rm /tmp/gl.tar.gz || true

# wappalyzer — wrapper script (npm installs to non-standard path, needs wrapper)
npm_install wappalyzer-cli
printf '#!/bin/bash\nnode /usr/local/lib/node_modules/wappalyzer-cli/bin/wappalyzer "$@"\n' \
  > /usr/local/bin/wappalyzer && chmod +x /usr/local/bin/wappalyzer

# LinkFinder
clone https://github.com/GerbenJavado/LinkFinder /opt/LinkFinder
pip_install -r /opt/LinkFinder/requirements.txt
ln -sf /opt/LinkFinder/linkfinder.py /usr/local/bin/linkfinder
chmod +x /opt/LinkFinder/linkfinder.py 2>/dev/null || true

# SecLists
clone https://github.com/danielmiessler/SecLists /opt/SecLists

# ════════════════════════════════════════════════════════════
# PHASE 2 — Web Application Testing
# ════════════════════════════════════════════════════════════
section "Phase 2 — Web Application Testing"

apt_install sqlmap

# semgrep — pip3 ONLY (apt python3-semgrep does NOT create the semgrep binary)
pip_install semgrep

pip_install mitmproxy arjun jsbeautifier graphql-cop graphw00f inql

# graphql-cop wrapper (pip installs module only, binary needs wrapper)
printf '#!/bin/bash\npython3 -m graphql_cop "$@"\n' > /usr/local/bin/graphql-cop && chmod +x /usr/local/bin/graphql-cop
printf '#!/bin/bash\npython3 -m graphw00f "$@"\n' > /usr/local/bin/graphw00f && chmod +x /usr/local/bin/graphw00f
pip_install PyJWT python-jose grpcio grpcio-tools websocket-client
pip_install blackboxprotobuf padding-oracle-attacker

# checkov — MUST use --ignore-installed (packaging conflict)
pip_force checkov

# git-dumper
pip_install git-dumper

# jwt_tool
clone https://github.com/ticarpi/jwt_tool /opt/jwt_tool
pip_install -r /opt/jwt_tool/requirements.txt
ln -sf /opt/jwt_tool/jwt_tool.py /usr/local/bin/jwt_tool
chmod +x /opt/jwt_tool/jwt_tool.py

# smuggler (HTTP Request Smuggling)
clone https://github.com/defparam/smuggler /opt/smuggler
ln -sf /opt/smuggler/smuggler.py /usr/local/bin/smuggler
chmod +x /opt/smuggler/smuggler.py

# tplmap (SSTI)
clone https://github.com/epinna/tplmap /opt/tplmap
pip_install -r /opt/tplmap/requirements.txt
ln -sf /opt/tplmap/tplmap.py /usr/local/bin/tplmap
chmod +x /opt/tplmap/tplmap.py

# wpscan via gem (NOT apt — apt version is outdated/broken on new Kali)
gem_install wpscan

# XXEinjector
clone https://github.com/enjoiz/XXEinjector /opt/XXEinjector

# CORScanner
clone https://github.com/chenjj/CORScanner /opt/CORScanner
pip_install -r /opt/CORScanner/requirements.txt

# ghauri (advanced SQLi)
pip_install ghauri
clone https://github.com/r0oth3x49/ghauri /opt/ghauri
pip_install -r /opt/ghauri/requirements.txt
ln -sf /opt/ghauri/ghauri.py /usr/local/bin/ghauri

# ysoserial + phpggc (deserialization)
mkdir -p /opt/ysoserial
curl -sL "https://github.com/frohoff/ysoserial/releases/latest/download/ysoserial-all.jar" \
  -o /opt/ysoserial/ysoserial.jar 2>/dev/null || true
clone https://github.com/ambionics/phpggc /opt/phpggc
ln -sf /opt/phpggc/phpggc /usr/local/bin/phpggc
chmod +x /opt/phpggc/phpggc

# graphw00f, clairvoyance
pip_install graphw00f clairvoyance

# grpcurl
go_install github.com/fullstorydev/grpcurl/cmd/grpcurl@latest

# syft, grype (supply chain)
curl -sSfL https://raw.githubusercontent.com/anchore/syft/main/install.sh | sh -s -- -b /usr/local/bin 2>/dev/null || true
curl -sSfL https://raw.githubusercontent.com/anchore/grype/main/install.sh | sh -s -- -b /usr/local/bin 2>/dev/null || true

# ════════════════════════════════════════════════════════════
# PHASE 3 — Active Directory & Windows
# ════════════════════════════════════════════════════════════
section "Phase 3 — Active Directory & Windows"

pip_install impacket certipy-ad pywhisker netexec bloodyAD ldeep pyrdp bloodhound

# theHarvester — MUST use apt (pip version is broken on newer Kali)
apt_install theharvester

# netexec + wifite — apt is correct (confirmed working)
apt_install netexec wifite

# crackmapexec → symlink to netexec (same tool, renamed in 2024)
ln -sf /usr/bin/netexec /usr/local/bin/crackmapexec 2>/dev/null || true

gem_install evil-winrm

# Impacket symlinks — CRITICAL: scripts are .py files, need impacket- prefix
for script in psexec smbexec wmiexec secretsdump GetUserSPNs GetNPUsers \
    ntlmrelayx lookupsid ticketer ticketConverter getST addcomputer \
    atexec dcomexec dpapi esentutl findDelegation goldenPac karmaSMB \
    netview nmapAnswerMachine ping6 raiseChild rpcdump sambaPipe \
    samrdump services sniffer sniff tstool; do
  if [ -f /usr/local/bin/${script}.py ]; then
    ln -sf /usr/local/bin/${script}.py /usr/local/bin/impacket-${script}
    chmod +x /usr/local/bin/${script}.py
  fi
done

# AD tools
clone https://github.com/dirkjanm/PKINITtools /opt/PKINITtools
pip_install -r /opt/PKINITtools/requirements.txt
clone https://github.com/topotam/PetitPotam /opt/PetitPotam
clone https://github.com/login-securite/DonPAPI /opt/DonPAPI
pip_install -r /opt/DonPAPI/requirements.txt
clone https://github.com/Ridter/noPac /opt/noPac
clone https://github.com/Dec0ne/KrbRelayUp /opt/KrbRelayUp
clone https://github.com/dirkjanm/CVE-2020-1472 /opt/CVE-2020-1472
clone https://github.com/cube0x0/CVE-2021-1675 /opt/PrintNightmare
clone https://github.com/dirkjanm/krbrelayx /opt/krbrelayx
pip_install dnspython ldap3 pyOpenSSL
clone https://github.com/fireeye/ADFSpoof /opt/ADFSpoof
pip_install -r /opt/ADFSpoof/requirements.txt
clone https://github.com/klezVirus/SysWhispers3 /opt/SysWhispers3
clone https://github.com/Hackndo/pyGPOAbuse /opt/pyGPOAbuse
pip_install -r /opt/pyGPOAbuse/requirements.txt
clone https://github.com/byt3bl33d3r/DeathStar /opt/DeathStar
pip_install -r /opt/DeathStar/requirements.txt
pip_install roadtools roadrecon
go_install github.com/ropnop/kerbrute@latest
# windapsearch — binary download (go install module path is broken)
echo -e "  ${BLUE}[BIN]${NC} windapsearch"
curl -sL "https://github.com/ropnop/windapsearch/releases/download/v0.0.11/windapsearch-linux-amd64" \
  -o /usr/local/bin/windapsearch 2>/dev/null && chmod +x /usr/local/bin/windapsearch && OK=$((OK+1)) || FAIL=$((FAIL+1))

# LDAP/SMB enum
apt_install enum4linux nbtscan smbmap smbclient ldap-utils
# enum4linux-ng — NOT on pip, use python module wrapper
printf '#!/bin/bash\npython3 -m enum4linux_ng "$@"\n' > /usr/local/bin/enum4linux-ng && chmod +x /usr/local/bin/enum4linux-ng && OK=$((OK+1)) || FAIL=$((FAIL+1))

# Responder, Coercer, Mitm6
apt_install responder
pip_install mitm6 coercer bloodyAD ldeep

# pyrdp
pip_install pyrdp

# ════════════════════════════════════════════════════════════
# PHASE 4 — Cloud
# ════════════════════════════════════════════════════════════
section "Phase 4 — Cloud"

pip_install awscli boto3 google-cloud-storage google-auth \
  scoutsuite prowler kube-hunter principalmapper \
  checkov s3scanner

# azure-cli
pip_install azure-cli 2>/dev/null || \
  curl -sL https://aka.ms/InstallAzureCLIDeb | bash 2>/dev/null || true

# enumerate-iam (AWS)
clone https://github.com/andresriancho/enumerate-iam /opt/enumerate-iam
pip_install -r /opt/enumerate-iam/requirements.txt
ln -sf /opt/enumerate-iam/enumerate-iam.py /usr/local/bin/enumerate-iam
chmod +x /opt/enumerate-iam/enumerate-iam.py

# azcopy
curl -sSL "https://aka.ms/downloadazcopy-v10-linux" | tar xz --strip-components=1 -C /usr/local/bin/ 2>/dev/null || true

# kubectl
curl -LO "https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl" 2>/dev/null \
  && install -m 0755 kubectl /usr/local/bin/kubectl && rm kubectl || true

# kubectx + kubens
clone https://github.com/ahmetb/kubectx /opt/kubectx
ln -sf /opt/kubectx/kubectx /usr/local/bin/kubectx
ln -sf /opt/kubectx/kubens /usr/local/bin/kubens

# kube-bench, helm
go_install github.com/aquasecurity/kube-bench@latest
curl https://raw.githubusercontent.com/helm/helm/main/scripts/get-helm-3 | bash 2>/dev/null || true

# Go cloud tools
go_install github.com/BishopFox/cloudfox@latest
go_install github.com/DataDog/stratus-red-team/v2/cmd/stratus@latest
go_install github.com/liamg/awswhoami@latest
go_install github.com/projectdiscovery/cloudlist/cmd/cloudlist@latest

# Container tools
go_install github.com/cdk-team/CDK/cmd/cdk@latest
go_install github.com/brompwnie/botb@latest
curl -sSL https://github.com/stealthcopter/deepce/releases/latest/download/deepce \
  -o /usr/local/bin/deepce && chmod +x /usr/local/bin/deepce 2>/dev/null || true
curl -sfL https://raw.githubusercontent.com/aquasecurity/trivy/main/contrib/install.sh | sh -s -- -b /usr/local/bin 2>/dev/null || true
curl -sSfL https://raw.githubusercontent.com/wagoodman/dive/main/get-dive.sh | sh 2>/dev/null || true

# cloud_enum, Pacu
clone https://github.com/initstring/cloud_enum /opt/cloud_enum
pip_install -r /opt/cloud_enum/requirements.txt
pip_install pacu

# ════════════════════════════════════════════════════════════
# PHASE 5 — Mobile Testing
# ════════════════════════════════════════════════════════════
section "Phase 5 — Mobile Testing"

apt_install apktool dex2jar android-tools-adb mono-complete mono-utils

# jadx — download zip (NOT apt — apt version is old)
mkdir -p /opt/jadx
curl -sSL "https://github.com/skylot/jadx/releases/download/v1.5.0/jadx-1.5.0.zip" \
  -o /tmp/jadx.zip 2>/dev/null && unzip -qo /tmp/jadx.zip -d /opt/jadx && \
  ln -sf /opt/jadx/bin/jadx /usr/local/bin/jadx && \
  ln -sf /opt/jadx/bin/jadx-gui /usr/local/bin/jadx-gui && rm /tmp/jadx.zip || true

# uber-apk-signer
mkdir -p /opt/uber-apk-signer
curl -sSL "https://github.com/patrickfav/uber-apk-signer/releases/download/v1.3.0/uber-apk-signer-1.3.0.jar" \
  -o /opt/uber-apk-signer/uber-apk-signer.jar 2>/dev/null || true
printf '#!/bin/bash\nexec java -jar /opt/uber-apk-signer/uber-apk-signer.jar "$@"\n' \
  > /usr/local/bin/uber-apk-signer && chmod +x /usr/local/bin/uber-apk-signer

# Frida tools
pip_install frida-tools objection apkleaks drozer

# reFlutter, hermes, cross-platform analysis
# NOTE: doldrums has no PyPI package — skip
pip_install reflutter androguard trufflehog3 hermes-dec hbctool "qrcode[pil]" Pillow lz4

# qrcode CLI wrapper
command -v qrcode >/dev/null 2>&1 || \
  printf '#!/bin/bash\npython3 -m qrcode "$@"\n' > /usr/local/bin/qrcode && \
  chmod +x /usr/local/bin/qrcode || true

# apk-mitm
npm_install apk-mitm js-beautify

# setup-frida-server script
cat > /usr/local/bin/setup-frida-server << 'FSCRIPT'
#!/bin/bash
FRIDA_VER=$(python3 -c "import frida; print(frida.__version__)" 2>/dev/null || pip3 show frida | grep Version | awk '{print $2}')
ARCH=$(adb shell getprop ro.product.cpu.abi 2>/dev/null | tr -d '\r')
case $ARCH in
  arm64-v8a) A="arm64" ;; armeabi-v7a) A="arm" ;;
  x86_64) A="x86_64" ;; x86) A="x86" ;; *) echo "Unknown: $ARCH"; exit 1 ;;
esac
wget -q "https://github.com/frida/frida/releases/download/${FRIDA_VER}/frida-server-${FRIDA_VER}-android-${A}.xz" -O /tmp/frida-server.xz
unxz /tmp/frida-server.xz && mv /tmp/frida-server "/tmp/frida-server-${A}"
adb push "/tmp/frida-server-${A}" /data/local/tmp/frida-server
adb shell chmod 755 /data/local/tmp/frida-server
echo "[+] Start: adb shell /data/local/tmp/frida-server &"
FSCRIPT
chmod +x /usr/local/bin/setup-frida-server

# drozer agent APK (v2.3.4 — repo moved to ReversecLabs, last APK release)
mkdir -p /opt/drozer
curl -sL "https://github.com/ReversecLabs/drozer/releases/download/2.3.4/drozer-agent-2.3.4.apk" \
  -o /opt/drozer/drozer-agent.apk 2>/dev/null || true

# TheFatRat — interactive tool, optional
clone https://github.com/Screetsec/TheFatRat /opt/TheFatRat
chmod +x /opt/TheFatRat/fatrat 2>/dev/null || true

# ════════════════════════════════════════════════════════════
# PHASE 6 — C2 & Post-Exploitation
# ════════════════════════════════════════════════════════════
section "Phase 6 — C2 & Post-Exploitation"

apt_install metasploit-framework iodine
curl https://sliver.sh/install | bash 2>/dev/null || true
go_install github.com/jpillora/chisel@latest
go_install github.com/nicocha30/ligolo-ng/cmd/proxy@latest
go_install github.com/nicocha30/ligolo-ng/cmd/agent@latest
go_install github.com/Ne0nd0g/merlin-agent/cmd/merlinagent@latest

clone https://github.com/BC-SECURITY/Empire /opt/Empire
pip_install -r /opt/Empire/requirements.txt
ln -sf /opt/Empire/empire /usr/local/bin/empire 2>/dev/null || true
clone https://github.com/nettitude/PoshC2 /opt/PoshC2
pip_install -r /opt/PoshC2/requirements.txt
clone https://github.com/t3l3machus/Villain /opt/Villain
pip_install -r /opt/Villain/requirements.txt
clone https://github.com/iagox86/dnscat2 /opt/dnscat2
cd /opt/dnscat2/client && make 2>/dev/null || true; cd /

# Payload generation
clone https://github.com/optiv/ScareCrow /opt/ScareCrow
cd /opt/ScareCrow && go build -o /usr/local/bin/ScareCrow . 2>/dev/null || true; cd /
clone https://github.com/sevagas/macro_pack /opt/macro_pack
pip_install donut-shellcode
go_install github.com/Binject/go-donut/cmd/godonuts@latest

# ════════════════════════════════════════════════════════════
# PHASE 7 — OSINT & Intelligence
# ════════════════════════════════════════════════════════════
section "Phase 7 — OSINT & Intelligence"

# NOTE: spiderfoot not on PyPI — install from git below
# NOTE: sherlock-project installs as binary 'sherlock' (not importable module)
pip_install shodan censys h8mail holehe maigret socialscan \
  duckduckgo-search ipinfo PyGithub

apt_install whois

# spiderfoot from git (not on PyPI)
clone https://github.com/smicallef/spiderfoot /opt/spiderfoot
pip_install -r /opt/spiderfoot/requirements.txt
printf '#!/bin/bash\npython3 /opt/spiderfoot/sf.py "$@"\n' > /usr/local/bin/spiderfoot
chmod +x /usr/local/bin/spiderfoot

clone https://github.com/lanmaster53/recon-ng /opt/recon-ng
pip_install -r /opt/recon-ng/REQUIREMENTS
ln -sf /opt/recon-ng/recon-ng /usr/local/bin/recon-ng

clone https://github.com/m8sec/CrossLinked /opt/CrossLinked
pip_install -r /opt/CrossLinked/requirements.txt

pip_install sherlock-project

go_install github.com/gwen001/github-subdomains@latest

# ════════════════════════════════════════════════════════════
# PHASE 8 — Passwords & Credentials
# ════════════════════════════════════════════════════════════
section "Phase 8 — Passwords & Credentials"

apt_install hashcat john hydra medusa cewl crunch ncrack

clone https://github.com/Mebus/cupp /opt/cupp
ln -sf /opt/cupp/cupp.py /usr/local/bin/cupp
chmod +x /opt/cupp/cupp.py

pip_install pypykatz
# NOTE: patator must use --no-deps (cx-oracle build fails, not needed for core use)
pip3 install --no-cache-dir --break-system-packages --no-deps patator 2>/dev/null || true

# Crypto libraries
pip_install pycryptodome hashpumpy cryptography sympy gmpy2 ecdsa

# Extract rockyou.txt from SecLists (stored compressed)
tar xzf /opt/SecLists/Passwords/Leaked-Databases/rockyou.txt.tar.gz \
  -C /opt/SecLists/Passwords/Leaked-Databases/ 2>/dev/null || true

# ════════════════════════════════════════════════════════════
# PHASE 9 — Binary Analysis & RE
# ════════════════════════════════════════════════════════════
section "Phase 9 — Binary Analysis & RE"

apt_install gdb radare2 ltrace strace binutils patchelf nasm \
  yara binutils-multiarch sleuthkit

pip_install pwntools floss capstone keystone-engine unicorn \
  ropgadget ropper angr yara-python

# pwndbg
clone https://github.com/pwndbg/pwndbg /opt/pwndbg
cd /opt/pwndbg && ./setup.sh 2>/dev/null || true; cd /

# GEF
bash -c "$(curl -sSL https://gef.blah.cat/sh)" 2>/dev/null || true

# Ghidra
if ! command -v ghidra &>/dev/null; then
  curl -sSL "https://github.com/NationalSecurityAgency/ghidra/releases/latest/download/ghidra_11.1_PUBLIC_20240607.zip" \
    -o /tmp/ghidra.zip 2>/dev/null && \
    unzip -q /tmp/ghidra.zip -d /opt && \
    ln -s /opt/ghidra_*/ghidraRun /usr/local/bin/ghidra && \
    rm /tmp/ghidra.zip 2>/dev/null || true
fi

# YARA rules
clone https://github.com/Yara-Rules/rules /opt/yara-rules

# Fuzzing
apt_install afl++
clone https://gitlab.com/akihe/radamsa /opt/radamsa
cd /opt/radamsa && make 2>/dev/null && ln -sf /opt/radamsa/bin/radamsa /usr/local/bin/radamsa || true; cd /
pip_install boofuzz

# Forensics
apt_install foremost dc3dd testdisk bulk-extractor exiftool
clone https://github.com/volatilityfoundation/volatility3 /opt/volatility3
pip_install -r /opt/volatility3/requirements.txt
ln -sf /opt/volatility3/vol.py /usr/local/bin/vol

# ════════════════════════════════════════════════════════════
# PHASE 10 — Network & WiFi
# ════════════════════════════════════════════════════════════
section "Phase 10 — Network & WiFi"

apt_install tcpdump tshark bettercap ettercap-text-only dsniff \
  sslstrip hping3 proxychains4 macchanger socat \
  responder aircrack-ng wireless-tools rfkill \
  hostapd-wpe ubertooth ncrack \
  sipvicious rtpbreak pjsua suricata \
  arpwatch netsniff-ng

apt_install hcxtools 2>/dev/null || true

# hcxdumptool (compile from source — apt version may be outdated)
clone https://github.com/ZerBea/hcxdumptool /opt/hcxdumptool
cd /opt/hcxdumptool && make && make install 2>/dev/null || true; cd /

# wifite via apt (confirmed working, pip version has issues)
apt_install wifite

pip_install mitm6 mitmproxy scapy bleak pyserial pyModbusTCP

clone https://github.com/lgandx/PCredz /opt/PCredz

# GoPhish
curl -sL "https://github.com/gophish/gophish/releases/download/v0.12.1/gophish-v0.12.1-linux-64bit.zip" \
  -o /tmp/gophish.zip 2>/dev/null && \
  unzip -q /tmp/gophish.zip -d /opt/gophish && \
  chmod +x /opt/gophish/gophish && \
  ln -s /opt/gophish/gophish /usr/local/bin/gophish && \
  rm /tmp/gophish.zip 2>/dev/null || true

go_install github.com/kgretzky/evilginx2@latest

# ════════════════════════════════════════════════════════════
# PHASE 11 — Specialist
# ════════════════════════════════════════════════════════════
section "Phase 11 — Specialist"

# Social Engineering
clone https://github.com/trustedsec/social-engineer-toolkit /opt/setoolkit
pip_install -r /opt/setoolkit/requirements.txt
pip_install o365spray
clone https://github.com/ryhanson/phishery /opt/phishery
clone https://github.com/ustayready/CredSniper /opt/CredSniper
pip_install -r /opt/CredSniper/requirements.txt

# Hardware/IoT
apt_install openocd flashrom avrdude minicom screen steghide sox binwalk exiftool
gem_install zsteg
pip_install stegoveritas

# AI/LLM
pip_install garak openai anthropic langchain transformers
npm_install promptfoo

# OSINT specialized
pip_install ghunt

# Purple Team
clone https://github.com/redcanaryco/atomic-red-team /opt/atomic-red-team
clone https://github.com/mitre/caldera /opt/caldera
pip_install -r /opt/caldera/requirements.txt

# Nuclei templates
nuclei -update-templates 2>/dev/null || true

# ════════════════════════════════════════════════════════════
# FINAL — PATH & Environment
# ════════════════════════════════════════════════════════════
section "Final Setup"

# Copy ALL Go binaries to system PATH (ensures everything accessible)
cp /root/go/bin/* /usr/local/bin/ 2>/dev/null || true

# Environment variables
cat > /etc/profile.d/rtexit-env.sh << 'ENVEOF'
export PATH="$PATH:/root/go/bin:/usr/local/bin:/opt/rtexit/scripts"
export SECLISTS='/opt/SecLists'
export GOPATH='/root/go'
ENVEOF
chmod +x /etc/profile.d/rtexit-env.sh

# Summary
echo ""
echo -e "${GREEN}${BOLD}════════════════════════════════════════════${NC}"
echo -e "${GREEN}${BOLD}  RTExit Native Install Complete!${NC}"
echo -e "${GREEN}${BOLD}════════════════════════════════════════════${NC}"
echo ""
echo -e "  ${CYAN}Install results:${NC}"
echo -e "  ${GREEN}✅ Successful: $OK${NC}"
echo -e "  ${RED}❌ Failed:     $FAIL${NC}"
echo ""
echo -e "  ${CYAN}Next steps:${NC}"
echo -e "  1. source /etc/profile.d/rtexit-aliases.sh"
echo -e "  2. source /etc/profile.d/rtexit-env.sh"
echo -e "  3. bash \$(dirname \$0)/verify/rt-verify-all.sh --quick"
echo ""
