# Samba server for sharing /mnt/k8s via SMB protocol

resource "ssh_resource" "samba_install" {
  host        = local.ssh_host
  user        = local.ssh_user
  port        = local.ssh_port
  private_key = local.ssh_private_key
  timeout     = "5m"

  when = "create"

  commands = [
    "echo 'Installing Samba server...'",
    "sudo apt-get update",
    "sudo DEBIAN_FRONTEND=noninteractive apt-get install -y samba samba-common-bin",
    "echo 'Samba installed successfully'"
  ]
}

resource "ssh_resource" "samba_config" {
  depends_on = [ssh_resource.samba_install]

  host        = local.ssh_host
  user        = local.ssh_user
  port        = local.ssh_port
  private_key = local.ssh_private_key
  timeout     = "3m"

  when = "create"

  commands = [
    "echo 'Configuring Samba share...'",
    "sudo cp /etc/samba/smb.conf /etc/samba/smb.conf.backup",
    "cat << 'EOF' | sudo tee -a /etc/samba/smb.conf\n\n[mnt]\n   comment = Server Mount Point Storage\n   path = /mnt\n   browseable = yes\n   read only = no\n   writable = yes\n   valid users = junv\n   create mask = 0775\n   directory mask = 0775\n   force user = junv\n   force group = junv\nEOF",
    "sudo mkdir -p /mnt",
    "sudo chown -R junv:junv /mnt",
    "sudo chmod -R 775 /mnt",
    "echo -e 'junv\\njunv' | sudo smbpasswd -a junv",
    "sudo smbpasswd -e junv",
    "sudo testparm -s",
    "sudo systemctl restart smbd",
    "sudo systemctl restart nmbd",
    "sudo systemctl enable smbd",
    "sudo systemctl enable nmbd",
    "sudo ufw allow Samba 2>/dev/null || echo 'UFW not active or Samba already allowed'",
    "echo 'Samba configuration completed!'"
  ]
}

output "samba_info" {
  value = <<EOT
Samba server has been configured!

Share Details:
  Share Name: mnt
  Path: /mnt
  User: junv

Access from macOS:
  1. In Finder, press Cmd+K
  2. Connect to: smb://192.168.1.2/mnt
  3. Username: junv
  4. Password: junv (CHANGE THIS IMMEDIATELY!)

Access from Linux:
  sudo mount -t cifs //192.168.1.2/mnt /mnt/remote -o username=junv,password=junv

Change Samba Password:
  ssh -p 22422 junv@192.168.1.2
  sudo smbpasswd junv

View Samba Status:
  ssh -p 22422 junv@192.168.1.2 "sudo systemctl status smbd"
EOT
}
