#!/bin/bash
# SERVIDOR INTERNO
# (CentOS 9)
alias "s"="sudo systemctl"

function instalar() {
    yum list installed "$1" &>/dev/null && echo "$1 já instalado" || sudo yum install -y "$1"
}

IP_EXTERNAL="20.60.0.1"
IP_INTERNAL="10.60.0.1"

sudo ifconfig enp0s8 $IP_EXTERNAL netmask 255.255.255.0
sudo ifconfig enp0s9 $IP_INTERNAL netmask 255.255.255.0

# instalar packages
if ! command -v node &> /dev/null || [[ "$(node -v)" != v24.* ]]; then
    echo "Configurando repositório do Node.js 24..."
    curl -fsSL https://rpm.nodesource.com/setup_24.x | sudo bash -
    sudo yum remove -y nodejs
fi
instalar nodejs

# instalar mod security e apache
instalar epel-release
instalar httpd
instalar mod_security
instalar mod_security_crs

instalar iptables-services
s stop firewalld
s disable firewalld
s mask firewalld
s enable iptables
sudo iptables -F

# nat
sudo sysctl -w net.ipv4.ip_forward=1
sudo iptables -t nat -F
sudo iptables -A FORWARD -i enp0s9 -o enp0s8 -j ACCEPT
sudo iptables -A FORWARD -i enp0s8 -o enp0s9 -m state --state ESTABLISHED,RELATED -j ACCEPT
sudo iptables -t nat -A POSTROUTING -o enp0s8 -j MASQUERADE
sudo iptables-save > /etc/sysconfig/iptables

sudo cp conf/httpd.conf /etc/httpd/conf/httpd.conf
sudo cp conf/modsecurity.conf /etc/httpd/conf/modsecurity.conf

# instalar juice-shop se nao existir
jspath="/var/juice-shop"
if [[ ! -f "$jspath/package.json" ]]; then
    sudo mkdir -p "$jspath"
    curl -L -o js.tar.gz "https://github.com/juice-shop/juice-shop/releases/download/v20.0.0/juice-shop-20.0.0_node24_linux_x64.tgz"
    sudo tar -xzvf js.tar.gz -C "$jspath" --strip-components=1
    rm js.tar.gz
    sudo chown -R $USER:$USER "$jspath"
fi

# correr juice shop via npm
cd "$jspath"
npm start