#!/bin/bash

SERVER=w2k3
#SERVER=w2k8r2
#SERVER=w2012

SHARE="\\\\$SERVER\share"
FILE="foo/foo"

SD1="O:BAG:S-1-5-21-544672039-3292642921-789916367-513D:(A;;0x001f01ff;;;SY)(A;;0x001f01ff;;;BA)(A;;0x001200a9;;;BU)"
SD2="O:S-1-5-21-2164988016-3932193065-851611966-1111G:LGD:P(A;;0x001f01ff;;;BU)"
SD3="O:BAG:S-1-5-21-544672039-3292642921-789916367-513D:P(A;;0x001f01ff;;;BU)"

SMBCACLS="smbcacls -A $SERVER.pw $SHARE $FILE"
echo $SMBCACLS

function die() {
    echo $*
    exit 1
}

function get_sd() {
    $SMBCACLS --sddl --query-security-info=0xffffffff
}

function set_sd() {
    local sd=$1
    local secinfo=$2
    local rc
    $SMBCACLS --sddl -S $sd --set-security-info=$secinfo
    rc=$?
    if [[ $rc -ne 0 ]]; then
	echo smbcacls failed with $rc
    fi
}

function check_sd() {
    local sd=$1
    local sd_old=$2
    local SD=$(get_sd)

    if [[ "x$sd" != "x$SD" ]]; then
	echo -n check_sd failed:
	if [[ "x$sd_old" = "x$SD" ]]; then
	    echo sd not changed
	else
	    echo got \"$SD\" instead of \"$sd\"
	    return 1
	fi
    fi
    return 0
}

function test_set_sd() {
    local sd1=$1
    local sd2=$2
    local si=$3
    local SD

    printf "test_set_sd with 0x%08x\n" $si

    set_sd $sd1 0xf
    check_sd $sd1 || die failed to reset SD1

    set_sd $sd2 $si
    check_sd $sd2 $sd1 || die failed to set SD2
}

#test_set_sd $SD1 $SD2 0
#test_set_sd $SD1 $SD3 0

for bit in $(seq 4 31); do
    si=$((2**bit | 0xf)) 
#    si=$((2**bit)) 
    test_set_sd $SD1 $SD2 $si
    test_set_sd $SD1 $SD3 $si
done

# while true; do
#     r=$RANDOM
#     test_set_sd $SD1 $SD2 $((r * 16))
#     test_set_sd $SD1 $SD3 $((r * 16))
#     test_set_sd $SD1 $SD2 $((r * 256))
#     test_set_sd $SD1 $SD3 $((r * 256))
#     test_set_sd $SD1 $SD2 $((r * 4096))
#     test_set_sd $SD1 $SD3 $((r * 4096))
#     test_set_sd $SD1 $SD2 $((r * 4096 * 16))
#     test_set_sd $SD1 $SD3 $((r * 4096 * 16))
# done
