#!/bin/bash
set -e

# Create users group if it doesn't exist
getent group users >/dev/null 2>&1 || groupadd -g 100 users

# Create alexz user with UID 1000 if not exists
if ! id -u alexz >/dev/null 2>&1; then
    # Remove any existing user with UID 1000 (e.g. ubuntu)
    existing_user=$(getent passwd 1000 | cut -d: -f1)
    if [ -n "$existing_user" ] && [ "$existing_user" != "alexz" ]; then
        userdel "$existing_user" 2>/dev/null || true
    fi
    useradd -u 1000 -g users -M -s /usr/sbin/nologin alexz
    echo "Created user alexz (UID 1000)"
fi

# Set Samba password from environment variable
if [ -n "$SMB_PASSWORD" ]; then
    echo -e "${SMB_PASSWORD}\n${SMB_PASSWORD}" | smbpasswd -a -s alexz
    echo "Samba password set for alexz"
else
    echo "WARNING: SMB_PASSWORD not set. Samba authentication will fail."
fi

# Ensure directories exist
mkdir -p /config /var/log/samba /run/samba /nas

# Ensure correct ownership
chown alexz:users /nas 2>/dev/null || true

echo "Starting supervisord..."
exec /usr/bin/supervisord -c /etc/supervisor/conf.d/supervisord.conf
