#!/bin/bash
#---------------------------------------------------------------
# Linux Lite - Lite Share Folder first-run setup
# Runs as root via pkexec. Bootstraps a single user account so
# they can use `net usershare` without root for the rest of time.
# Assumes a freshly installed Linux Lite: no /etc/samba/smb.conf
# customisation, no smbd running, no Samba password set.
#
# argv[1]               username to enrol
# argv[1]=--password-only argv[2] = username  (skip everything
#                       except the smbpasswd step; used by the
#                       "Change network password" UI)
# stdin (first line)    new Samba password (optional — if blank,
#                       smbpasswd is skipped)
#---------------------------------------------------------------

set -e

export PATH="/usr/sbin:/usr/bin:/sbin:/bin"

PASSWORD_ONLY=0
if [ "$1" = "--password-only" ]; then
    PASSWORD_ONLY=1
    shift
fi

USER_TO_ADD="${1:-}"

if [ -z "$USER_TO_ADD" ]; then
    echo "lite-share-folder-setup: no user supplied" >&2
    exit 2
fi

if ! id -u "$USER_TO_ADD" >/dev/null 2>&1; then
    echo "lite-share-folder-setup: user '$USER_TO_ADD' does not exist" >&2
    exit 2
fi

# Read password from stdin (first line). Optional.
SMB_PASSWORD=""
if [ -t 0 ]; then
    # Stdin is a tty — nothing was piped, just leave blank.
    :
else
    IFS= read -r SMB_PASSWORD || true
fi

SMB_CONF="/etc/samba/smb.conf"
SMB_CONF_CHANGED=0

# ---------------------------------------------------------------
# Full setup path
# ---------------------------------------------------------------

if [ "$PASSWORD_ONLY" -eq 0 ]; then

    # 1. Ensure the sambashare group exists. samba-common's postinst
    #    normally creates it, but be defensive on stripped images.
    if ! getent group sambashare >/dev/null 2>&1; then
        groupadd --system sambashare
    fi

    # 2. Add the user to sambashare.
    if ! id -nG "$USER_TO_ADD" | tr ' ' '\n' | grep -qx sambashare; then
        gpasswd -a "$USER_TO_ADD" sambashare >/dev/null
    fi

    # 3. Make sure /etc/samba/smb.conf has the usershare stanza. On a
    #    stock Ubuntu/Debian samba install it's there; on a system
    #    where smb.conf has been hand-edited or is missing entirely,
    #    we add it. The append-as-extra-[global] form is safe: samba
    #    accepts multiple [global] sections and merges them.
    if [ ! -f "$SMB_CONF" ]; then
        mkdir -p "$(dirname "$SMB_CONF")"
        cat > "$SMB_CONF" <<'EOF'
# Created by lite-share-folder-setup on a fresh Linux Lite install.

[global]
   workgroup = WORKGROUP
   server string = %h server
   security = user
   map to guest = bad user
   passdb backend = tdbsam

   usershare path = /var/lib/samba/usershares
   usershare max shares = 100
   usershare allow guests = yes
   usershare owner only = yes
EOF
        SMB_CONF_CHANGED=1
    elif ! grep -qiE '^[[:space:]]*usershare[[:space:]]' "$SMB_CONF"; then
        cat >> "$SMB_CONF" <<'EOF'

# Added by lite-share-folder-setup so right-click → Share Folder works
# without further smb.conf editing. Safe to leave in place even if you
# later configure Samba through Lite Network Shares.
[global]
   usershare path = /var/lib/samba/usershares
   usershare max shares = 100
   usershare allow guests = yes
   usershare owner only = yes
EOF
        SMB_CONF_CHANGED=1
    fi

    # 4. Ensure the usershare directory exists with the right perms.
    USERSHARE_DIR="/var/lib/samba/usershares"
    if [ ! -d "$USERSHARE_DIR" ]; then
        mkdir -p "$USERSHARE_DIR"
    fi
    chgrp sambashare "$USERSHARE_DIR" 2>/dev/null || true
    chmod 1770 "$USERSHARE_DIR" 2>/dev/null || true

    # 5. Enable smbd + nmbd. enable --now starts them if stopped.
    systemctl enable smbd >/dev/null 2>&1 || true
    systemctl enable nmbd >/dev/null 2>&1 || true
    systemctl is-active --quiet smbd || systemctl start smbd >/dev/null 2>&1 || true
    systemctl is-active --quiet nmbd || systemctl start nmbd >/dev/null 2>&1 || true

    # 6. If we edited smb.conf, restart so the new config is in effect.
    if [ "$SMB_CONF_CHANGED" -eq 1 ]; then
        systemctl restart smbd >/dev/null 2>&1 || true
        systemctl restart nmbd >/dev/null 2>&1 || true
    fi

    # 7. firewalld: open Samba.
    if systemctl is-active --quiet firewalld 2>/dev/null; then
        firewall-cmd --permanent --add-service=samba >/dev/null 2>&1 || true
        firewall-cmd --reload >/dev/null 2>&1 || true
    fi
fi

# ---------------------------------------------------------------
# Samba password step (also reached via --password-only)
# ---------------------------------------------------------------

if [ -n "$SMB_PASSWORD" ]; then
    # pdbedit will exit 0 with no output if the account is missing,
    # so grep for the literal "user:" prefix.
    if pdbedit -L 2>/dev/null | grep -q "^${USER_TO_ADD}:"; then
        printf '%s\n%s\n' "$SMB_PASSWORD" "$SMB_PASSWORD" \
            | smbpasswd -s "$USER_TO_ADD" >/dev/null
    else
        printf '%s\n%s\n' "$SMB_PASSWORD" "$SMB_PASSWORD" \
            | smbpasswd -a -s "$USER_TO_ADD" >/dev/null
    fi
fi

exit 0
