#!/bin/bash

# Tunnel Host Setup Script for Linux
# This script sets up SSH server and prepares the system for SMB and printer tunneling

set -e

echo "=================================================="
echo "   Tunnel Host Setup for SMB & Printing"
echo "=================================================="

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'cat 
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Check if running as root
if [ "$EUID" -ne 0 ]; then
    echo -e "${RED}Please run as root (sudo ./setup-tunnel-host.sh)${NC}"
    exit 1
fi

# Configuration
SSH_PORT="5022"
SMB_SHARE_DIR="/home/smb_share"
USERNAME="$SUDO_USER"

print_status() {
    echo -e "${GREEN}[+]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[!]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# Install required packages
print_status "Installing required packages..."
apt-get update
apt-get install -y openssh-server samba net-tools ufw

# Create SMB share directory
print_status "Creating SMB share directory..."
mkdir -p "$SMB_SHARE_DIR"
chown "$USERNAME:$USERNAME" "$SMB_SHARE_DIR"
chmod 755 "$SMB_SHARE_DIR"

# Configure Samba
print_status "Configuring Samba..."
cat >> /etc/samba/smb.conf << EOF

# Tunneled SMB Share
[tunnel-share]
    path = $SMB_SHARE_DIR
    available = yes
    valid users = $USERNAME
    read only = no
    browseable = yes
    public = no
    writable = yes
    create mask = 0644
    directory mask = 0755
EOF

# Set Samba password
print_status "Setting up Samba user..."
if ! pdbedit -L | grep -q "$USERNAME"; then
    smbpasswd -a "$USERNAME"
else
    print_warning "Samba user $USERNAME already exists"
fi

# Restart Samba
print_status "Restarting Samba service..."
systemctl restart smbd
systemctl enable smbd

# Configure SSH Server
print_status "Configuring SSH server..."
cp /etc/ssh/sshd_config /etc/ssh/sshd_config.backup

cat > /etc/ssh/sshd_config << EOF
# SSH Server Configuration for Tunneling
Port $SSH_PORT
Protocol 2
HostKey /etc/ssh/ssh_host_rsa_key
HostKey /etc/ssh/ssh_host_ecdsa_key
HostKey /etc/ssh/ssh_host_ed25519_key

# Security Settings
PermitRootLogin no
PubkeyAuthentication yes
PasswordAuthentication no
PermitEmptyPasswords no
ChallengeResponseAuthentication no

# Tunnel Settings
AllowTcpForwarding yes
GatewayPorts no
X11Forwarding no
PrintMotd no
AcceptEnv LANG LC_*
Subsystem sftp /usr/lib/openssh/sftp-server

# Allow specific user
AllowUsers $USERNAME
EOF

# Create SSH directory for user
sudo -u "$USERNAME" mkdir -p "/home/$USERNAME/.ssh"
sudo -u "$USERNAME" chmod 700 "/home/$USERNAME/.ssh"

# Restart SSH service
print_status "Restarting SSH service..."
systemctl restart ssh
systemctl enable ssh

# Configure firewall
print_status "Configuring firewall..."
ufw --force enable
ufw allow "$SSH_PORT/tcp"
ufw allow 445/tcp  # SMB (local only)
ufw allow 631/tcp  # IPP (local only)

# Display system information
print_status "Gathering system information..."
SERVER_IP=$(hostname -I | awk '{print $1}')
PUBLIC_IP=$(curl -s ifconfig.me || echo "Unknown")

echo ""
echo "=================================================="
echo "           SETUP COMPLETE"
echo "=================================================="
echo "Server Local IP: $SERVER_IP"
echo "Server Public IP: $PUBLIC_IP"
echo "SSH Port: $SSH_PORT"
echo "SMB Share Path: $SMB_SHARE_DIR"
echo "Username: $USERNAME"
echo ""
echo "NEXT STEPS:"
echo "1. Transfer your public key to: /home/$USERNAME/.ssh/authorized_keys"
echo "2. chmod 600 /home/$USERNAME/.ssh/authorized_keys"
echo "3. Configure router to forward port $SSH_PORT to $SERVER_IP"
echo "4. Run the Windows client script"
echo "=================================================="

# Create management script
cat > /home/$USERNAME/manage-tunnel.sh << 'EOF'
#!/bin/bash
# Management script for tunnel host

case "$1" in
    status)
        echo "=== SSH Tunnel Status ==="
        systemctl status ssh
        echo ""
        echo "=== Samba Status ==="
        systemctl status smbd
        echo ""
        echo "=== Active SSH Connections ==="
        netstat -tlnp | grep :5022
        echo ""
        echo "=== Active Tunnels ==="
        ss -tlnp | grep -E ":(4450|8631|9100)"
        ;;
    restart)
        sudo systemctl restart ssh smbd
        echo "Services restarted"
        ;;
    logs)
        journalctl -u ssh -u smbd -f
        ;;
    share-info)
        echo "=== SMB Share Information ==="
        smbstatus
        echo ""
        echo "=== Share Contents ==="
        ls -la /home/smb_share/
        ;;
    *)
        echo "Usage: $0 {status|restart|logs|share-info}"
        ;;
esac
EOF

chmod +x /home/$USERNAME/manage-tunnel.sh
print_status "Management script created: /home/$USERNAME/manage-tunnel.sh"