#!/bin/bash

# Update packages
echo "Updating package lists..."
yes | sudo apt-get update

# Install Samba
echo "Installing Samba..."
yes | sudo apt install samba

# Create the folders
echo "Creating the public, protected and private folders..."
sudo mkdir -p /share/public
sudo mkdir /share/protected
sudo mkdir /share/private

# Add smbgroup group to the system
echo "Adding smbgroup to the system..."
sudo groupadd -f smbgroup 

# Create the smbuser user as part of smbgroup
echo "Creating the smbuser user as part of smbgroup..."
sudo useradd --system --no-create-home --group smbgroup -s /bin/false smbuser

# Creating user2
echo "Creating user2..."
sudo useradd -M -s /usr/sbin/nologin user2

# Setting ownership and permissions for public and protected folders
echo "Setting ownership and permissions for public and protected folders..."
sudo chown -R smbuser:smbgroup /share/public
sudo chown -R smbuser:smbgroup /share/protected
sudo chmod -R g+w /share/public
sudo chmod -R g+w /share/protected

# Setting ownership and permissions for private folder
echo "Setting folder permissions for user2..."
sudo chown -R user2:user2 /share/private

# Adding user2 to Samba
echo "Adding user2. Please enter a password..."
sudo smbpasswd -a user2

# Stop the Samba service
echo "Stopping the Samba service..."
sudo systemctl stop smbd

# Backup the default configuration file
echo "Backing up the default Samba config file..."
sudo mv /etc/samba/smb.conf /etc/samba/smb.conf.bak

# Create smb config file with custom settings
sudo bash -c 'cat > /etc/samba/smb.conf << EOF
[global]
server string = basic file share server
workgroup = WORKGROUP
security = user
map to guest = Bad User
name resolve order = bcast host

[public]
path = /share/public
force user = smbuser
force group = smbgroup
create mask = 0664
force create mode = 0664
directory mask = 0775
force directory mode = 0775
public = yes
writable = yes

[protected]
path = /share/protected
force user = smbuser
force group = smbgroup
create mask = 0664
force create mode = 0664
directory mask = 0775
force directory mode = 0775
public = yes
writable = no

[private]
path = /share/private
valid users = user2
read only = no
browseable = no
directory mask = 0700
create mask = 0600
EOF'

# Start Samba
echo "Starting the Samba service..."
sudo systemctl start smbd

# Get the current hostname
hostname=$(hostname)

# Define the other parts of the message
final_message="massi.net's samba_script.sh has completed.\nThis device's hostname is $hostname"

# Echo the final message
echo "$final_message"