#!/usr/bin/env bash

# Install required packages
sudo apt install -y tor tor-geoipdb nginx

# Configure Tor for hidden services
TOR_DEST="/etc/tor/torrc.d"
HIDDEN_DIR="/srv/tor/nginx_hidden_service"
HIDDEN_CONF="${TOR_DEST}/002_nginx.conf"

# Create directories and set permissions
sudo mkdir -p ${TOR_DEST} && sudo mkdir -p ${HIDDEN_DIR}
sudo chown -R debian-tor.debian-tor ${HIDDEN_DIR}
sudo chmod 2700 ${HIDDEN_DIR} && sudo chmod -x ${TOR_DEST}

# Configure Nginx
sudo tee /etc/nginx/sites-available/default << EOF
server {
    listen 127.0.0.1:80;
    server_name localhost;

    location / {
        root /var/www/html;
        index index.html;
    }
}
EOF

# Create Tor hidden service configuration for Nginx
cat <<EOF | sudo tee ${HIDDEN_CONF} >/dev/null
HiddenServiceDir ${HIDDEN_DIR}
HiddenServicePort 80 127.0.0.1:80
EOF

# Restart Tor service
sudo /etc/init.d/tor restart

echo "The hostname for the Nginx hidden service is:"
cat ${HIDDEN_DIR}/hostname

echo "You can access it using Tor Browser or torsocks with the following command:"
echo "torsocks curl http://$(cat ${HIDDEN_DIR}/hostname)"
