#!/bin/bash
set -e

# --- CONFIGURATION ---
HOSTNAME="dc0"
DOMAIN_REALM="LAB.BALDWINIT.ORG"
DOMAIN_NETBIOS="LAB"
ADMIN_PASS="h$$1iG00gl31177%%"
STATIC_IP="192.168.1.5" # CHANGE THIS to your VM's static IP
NETMASK="24"            # Change if not /24

# 2. Install Dependencies
apt update
apt install -y samba-ad-dc krb5-user winbind libnss-winbind libpam-winbind dnsutils

# 3. Stop Conflicting Standalone Services
systemctl stop smbd nmbd winbind
systemctl disable smbd nmbd winbind
systemctl unmask samba-ad-dc

# 4. Clean Configs
rm -f /etc/samba/smb.conf
rm -f /etc/krb5.conf

# 5. Provision Domain
# --option ensures Samba binds to the correct interface
samba-tool domain provision \
  --server-role=dc \
  --use-rfc2307 \
  --dns-backend=SAMBA_INTERNAL \
  --realm="$DOMAIN_REALM" \
  --domain="$DOMAIN_NETBIOS" \
  --adminpass="$ADMIN_PASS" \
  --option="interfaces=lo $STATIC_IP/$NETMASK" \
  --option="bind interfaces only=yes"

# 6. Configure DNS for Self-Resolution
# 1. Set Hostname & Hosts (CRITICAL for Samba Provisioning)
echo "$HOSTNAME" > /etc/hostname \
      hostnamectl set-hostname "$HOSTNAME"
echo "$STATIC_IP $HOSTNAME.$DOMAIN_REALM $HOSTNAME" \
      >> /etc/hosts
echo "127.0.0.1 localhost" > /etc/resolv.conf
cp /var/lib/samba/private/krb5.conf /etc/krb5.conf
echo "nameserver $STATIC_IP" > /etc/resolv.conf \
echo "search $DOMAIN_REALM" >> /etc/resolv.conf

# 7. Enable and Start AD DC
systemctl enable samba-ad-dc
systemctl start samba-ad-dc

# 8. Verification
echo "--- Verification ---"
samba-tool domain level show
systemctl status samba-ad-dc --no-pager
echo "DC Setup Complete. Point your physical router's DNS to $STATIC_IP."   



bind to 192.168.1.5:53 TCP - NT_STATUS_ADDRESS_NOT_ASSOCIATED