#!/usr/bin/env bash
set -euo pipefail

# === PROMPT USER ===
read -rp "📂 Enter the folder you want to share (absolute path): " SHARE_PATH
read -rp "📍 Enter the mount point name (e.g., data, backups, media): " MOUNT_POINT
read -rp "👤 Enter the Samba username: " SMB_USER

# Ensure SHARE_PATH is absolute
if [[ "$SHARE_PATH" != /* ]]; then
  echo "❌ Please provide an absolute path (starting with /)"
  exit 1
fi

# Detect distro family
if [ -f /etc/os-release ]; then
  . /etc/os-release
  DISTRO_FAMILY=$ID
else
  echo "❌ Cannot detect OS type"
  exit 1
fi

install_samba() {
  if ! command -v smbd >/dev/null 2>&1 && ! command -v smb >/dev/null 2>&1; then
    echo "📦 Installing Samba..."
    case "$DISTRO_FAMILY" in
      ubuntu|debian)
        apt-get update -y
        DEBIAN_FRONTEND=noninteractive apt-get install -y samba samba-common-bin
        ;;
      almalinux|rocky|centos|rhel|fedora)
        dnf install -y samba samba-client
        ;;
      *)
        echo "❌ Unsupported distro: $DISTRO_FAMILY"
        exit 1
        ;;
    esac
  fi
}

# Install Samba
install_samba

# Stop AD-DC service if it’s installed
systemctl disable --now samba-ad-dc 2>/dev/null || true

# Ensure directory exists
mkdir -p "$SHARE_PATH"

# Ensure user exists (no home, no login)
if ! id -u "$SMB_USER" >/dev/null 2>&1; then
  echo "ℹ️  Creating system user $SMB_USER (no home, no login)"
  useradd -M -s /usr/sbin/nologin "$SMB_USER"
fi

# Set directory ownership
chown -R "$SMB_USER":"$SMB_USER" "$SHARE_PATH"

# Backup smb.conf once
if [ -f /etc/samba/smb.conf ] && [ ! -f /etc/samba/smb.conf.bak ]; then
  cp -a /etc/samba/smb.conf /etc/samba/smb.conf.bak
fi

# Use the mount point name as the share name
SHARE_NAME="$MOUNT_POINT"

# Remove any old section with same name
awk -v name="[$SHARE_NAME]" '
  BEGIN {skip=0}
  /^\[/ {
    if ($0 == name) {skip=1; next}
    else {skip=0}
  }
  skip==0 {print}
' /etc/samba/smb.conf > /etc/samba/smb.conf.tmp
mv /etc/samba/smb.conf.tmp /etc/samba/smb.conf

# Append new share config
cat <<EOF >> /etc/samba/smb.conf

[$SHARE_NAME]
   path = $SHARE_PATH
   browseable = yes
   read only = no
   guest ok = no
   valid users = $SMB_USER
   create mask = 0664
   directory mask = 0775
EOF

# Validate config
testparm -s >/dev/null

# Prompt for Samba password
echo "🔑 Set a Samba password for $SMB_USER:"
smbpasswd -a "$SMB_USER"
smbpasswd -e "$SMB_USER"

# Open firewall
if command -v ufw >/dev/null 2>&1; then
  ufw allow Samba || true
elif command -v firewall-cmd >/dev/null 2>&1; then
  firewall-cmd --permanent --add-service=samba || true
  firewall-cmd --reload || true
fi

# Enable and start services
case "$DISTRO_FAMILY" in
  ubuntu|debian)
    systemctl enable --now smbd
    systemctl enable --now nmbd 2>/dev/null || true
    ;;
  almalinux|rocky|centos|rhel|fedora)
    systemctl enable --now smb
    systemctl enable --now nmb
    ;;
esac

IP_ADDR="$(hostname -I | awk '{print $1}')"

echo
echo "✅ Samba share created!"
echo "   Path:   $SHARE_PATH"
echo "   User:   $SMB_USER"
echo "   Share:  \\\\$IP_ADDR\\$SHARE_NAME"
echo
echo "Test with: smbclient -L //$IP_ADDR -U $SMB_USER"
