#!/bin/sh

# Fail fast if proxy not provided
if [ -z "$proxy" ]; then
	  echo "Error: You must provide a proxy address using the 'proxy' environment variable (e.g., 10.11.22.33:12345)"
	    exit 1
fi

# Extract IP and port
proxy_ip=$(echo "$proxy" | cut -d: -f1)
proxy_port=$(echo "$proxy" | cut -d: -f2)

# Generate redsocks config
cat > /etc/redsocks.conf <<EOF
base {
  log_debug = on;
  log_info = on;
  daemon = on;
  redirector = iptables;
}

redsocks {
  local_ip = 127.0.0.1;
  local_port = 12345;
  ip = ${proxy_ip};
  port = ${proxy_port};
  type = http-relay;
}
EOF

# Start redsocks
redsocks -c /etc/redsocks.conf

# Redirect HTTP and HTTPS traffic
iptables -t nat -A OUTPUT -p tcp --dport 80 -j REDIRECT --to-port 12345
iptables -t nat -A OUTPUT -p tcp --dport 443 -j REDIRECT --to-port 12345

# print out iptables config
iptables -t nat -L -v -n

# Drop into shell or run CMD
exec sh

