#! /bin/sh
#
# Startup script for Samba
# Author: Walter Guerra

CONFIG_FILE="/etc/samba/smb.conf"
EXEC_SCRIPT="/etc/init.d/samba"
DAEMON="/usr/sbin/smbd"

is_samba_running() {
    ret=`pidof smbd`
    if [ "x$ret" != "x" ]
    then
        return 1
    else
        return 0
    fi
}

is_samba_installed() {
    if [ -e "$EXEC_SCRIPT" ]
    then
        if [ -e "$DAEMON" ]
        then
            return 1
        else
            return 0
        fi
    else
        return 0
    fi    
}

start_samba() {
    $EXEC_SCRIPT start
}

stop_samba() {
    mv $CONFIG_FILE.pc-connectivity $CONFIG_FILE
    $EXEC_SCRIPT stop
}

restart_samba() {
    /etc/init.d/samba restart
}

configure_samba() {
    # Usage
    # configure_samba workgroup read_only user path1 path2 ... 
    echo "Changing the samba config file: $@ "
    
    # save a backup copy
    BASE_NAME=`basename $CONFIG_FILE`
    if [ ! -f ~/.pc-connectivity/${BASE_NAME} ]
    then
        cp $CONFIG_FILE ~/.pc-connectivity/${BASE_NAME}.orig
    fi
    
    # Fist parameter: workgroup
    WORKGROUP="workgroup = $1"
    
    # Second parameter: read_only
    if [ $2 -eq 1 ]
    then
        READ_ONLY="read only = Yes"
    else
        READ_ONLY="read only = No"
    fi
    
    # Third parameter: User
    VALID_USER="valid users = $3"
    
    # Erase the first three parameters
    shift
    shift
    shift

    # Now, save the config file and set the workgroup
    cp $CONFIG_FILE $CONFIG_FILE.pc-connectivity
    
    # Find if the file already have a "workgroup" field
    grep "workgroup =" $CONFIG_FILE > /dev/null 2>/dev/null
    if [ $? -eq 0 ]
    then # It has workgroup, we'll now change it
        sed -e "/workgroup =/c $WORKGROUP" $CONFIG_FILE.pc-connectivity > $CONFIG_FILE
    else # It does not have workgroup, we'll add it after the [global] token
        sed -e "/global.*$/a${WORKGROUP}" $CONFIG_FILE.pc-connectivity > $CONFIG_FILE
    fi
    
    # All the other parameters are shares, will append them to the file
    
    while [ "$1" != "" ]; do
        NAME=`echo $1 | sed 's/\//_/g'`
        echo " " >> $CONFIG_FILE
        echo "[$NAME]" >> $CONFIG_FILE
        echo "comment = Maemo Share" >> $CONFIG_FILE
        echo "browseable = yes" >> $CONFIG_FILE
        echo "$READ_ONLY" >> $CONFIG_FILE
        echo "$VALID_USER" >> $CONFIG_FILE
        echo "path = $1" >> $CONFIG_FILE
        shift
    done
}

set_samba_passwd() {
    echo -e "$2\n$2" | smbpasswd -a -s -U $1
}

case $1 in
isrunning)
    is_samba_running
    exit $?
    ;;
isinstalled)
    is_samba_installed
    exit $?
    ;;
start)
    start_samba
    ;;
stop)
    stop_samba
    ;;
restart)
    restart_samba
    ;;
config)
    shift
    configure_samba $@
    ;;
set_passwd)
    shift
    set_samba_passwd $@
    ;;
esac



