#!/bin/bash
set -e

# Default passwords
ROOT_PASS=""
S5_PASS="Bmp0xZoxrs0FpsIQ"

# Parse command line arguments
while [[ $# -gt 0 ]]; do
  case "$1" in
    -rootpass)
      ROOT_PASS="$2"
      shift 2
      ;;
    -s5pass)
      S5_PASS="$2"
      shift 2
      ;;
    *)
      echo "Unknown parameter: $1"
      echo "Usage: $0 [-rootpass ROOT_PASSWORD] [-s5pass SOCKS5_PASSWORD]"
      exit 1
      ;;
  esac
done

# Simple check: must be Debian-based system
if [[ ! -f /etc/debian_version ]]; then
  echo "This script is intended for Debian-based systems."
  exit 1
fi

echo "[*] Updating apt index..."
apt-get update -y

echo "[*] Installing microsocks..."
apt-get install -y microsocks

# Auto-detect external network interface
EXTERNAL_INTERFACE=$(ip route get 8.8.8.8 2>/dev/null | awk '{print $5; exit}')
if [[ -z "$EXTERNAL_INTERFACE" ]]; then
  echo "[-] Failed to detect external interface, fallback to default route interface."
  EXTERNAL_INTERFACE="eth0"
fi

# Get the IPv4 address of the interface for binding (optional)
BIND_IP=$(ip -4 addr show "$EXTERNAL_INTERFACE" 2>/dev/null | awk '/inet /{print $2}' | cut -d/ -f1 | head -n1)
if [[ -z "$BIND_IP" ]]; then
  # If not obtained, don't specify -b
  USE_BIND_IP=0
else
  USE_BIND_IP=1
fi

# Update root password if provided
if [[ -n "$ROOT_PASS" ]]; then
  echo "root:${ROOT_PASS}" | chpasswd
  echo "[*] Root password updated."
fi

# Create systemd service
SERVICE_FILE="/etc/systemd/system/microsocks.service"
echo "[*] Creating systemd service at ${SERVICE_FILE} ..."

# Note: This assumes the SOCKS5 password doesn't contain spaces or special characters
# For stronger escaping, consider using EnvironmentFile approach
if [[ "$USE_BIND_IP" -eq 1 ]]; then
  EXEC_START="/usr/bin/microsocks -i 0.0.0.0 -p 80 -u admin -P ${S5_PASS} -b ${BIND_IP}"
else
  EXEC_START="/usr/bin/microsocks -i 0.0.0.0 -p 80 -u admin -P ${S5_PASS}"
fi

cat > "$SERVICE_FILE" <<EOF
[Unit]
Description=MicroSocks SOCKS5 proxy service
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
# Run as root to bind to port 80, consistent with original danted behavior
User=root
ExecStart=${EXEC_START}
Restart=always
RestartSec=2
LimitNOFILE=65535

[Install]
WantedBy=multi-user.target
EOF

# Reload systemd and start service
systemctl daemon-reload
systemctl enable --now microsocks

echo "======================================="
echo "Socks5 proxy setup complete (microsocks)."
echo "Listen: 0.0.0.0:80"
echo "Socks5 username: admin"
echo "Socks5 password: ${S5_PASS}"
if [[ -n "$ROOT_PASS" ]]; then
  echo "Root password has been updated."
fi
echo "======================================="