#! /bin/bash

TARGET=$3
LAUNCHCTL=/bin/launchctl
SERVERADMIN=/usr/sbin/serveradmin
GREP=/usr/bin/grep
XXD=/usr/bin/xxd
KILLALL=/usr/bin/killall

if [ "$TARGET" = "" ]; then
    echo \$TARGET must be set
    exit 1
fi

# If we are not installing to /, we don't need to suspend any services, but
# we still might have to fix up the TDB files.
if [ "$TARGET" != "/" ]; then
    KILLALL=true
    LAUNCHCTL=true
    SERVERADMIN=true
else

    if [ -x $SERVERADMIN ]; then
        # On Server, the "smb" service handles both smbd and nmbd
        SERVICES=smb
    else
        # On Desktop, we need separate service name for every launchd task
        SERVICES="smbd nmbd swat"
    fi
fi

RUNNING=""

stop_service()
{
    service=$1
    if [ -x $SERVERADMIN ]; then
        $SERVERADMIN stop $service
    else
        $LAUNCHCTL stop org.samba.$service
        $LAUNCHCTL unload /System/Library/LaunchDaemons/$service.plist
    fi
}

start_service()
{
    service=$1

    if [ -x $SERVERADMIN ]; then
        $SERVERADMIN start $1
    else
        $LAUNCHCTL load /System/Library/LaunchDaemons/$service.plist
    fi
}

running_service()
{
    service=$1
    if [ -x $SERVERADMIN ]; then
        # serveradmin output for a running process is
        #       smb:state = "RUNNING"
        state=$(
        $SERVERADMIN status $1 | \
            perl -ne "/$service:state = \"(.+)\"/ && print \"\$1\n\";"
            )

        [[ "$state" = "RUNNING" ]]
    else
        # WARNING: The grep will hang unless launchctl is run as root.
        $LAUNCHCTL list | $GREP -q org.samba.$service
    fi
}

if [ "$TARGET" == "/" ]; then
    for s in $SERVICES ; do
        if running_service $s ; then
            RUNNING="$RUNNING $s"
        fi
    done

    for s in $RUNNING ; do
        stop_service $s
    done

    # Irrespective of whether the tools said they were running, we need to
    # make doubly sure that these processes are stopped.
    for pass in 1 2 ; do
        $KILLALL -TERM smbd nmbd swat
        sleep 1
    done
fi

find "$TARGET/var/db/samba" "$TARGET/var/samba" -name \*.tdb | while read tdb ; do
    echo '0000028: 0000 0000' | $XXD -r - "$tdb"
done

if [ "$TARGET" == "/" ]; then
    for s in $RUNNING ; do
        start_service $s
    done
fi
