HEX
Server: Apache/2.2.34 (Unix) mod_fastcgi/mod_fastcgi-SNAP-0910052141
System: Linux Kou-Etsu-Dou 4.4.59+ #25556 SMP PREEMPT Thu Mar 4 18:03:46 CST 2021 x86_64
User: hosam (1026)
PHP: 7.2.29
Disabled: NONE
Upload Files
File: //volume1/@appstore/DNSServer/script/regen_domain_hash.sh
#!/bin/bash

_safe_jq2file()
{
    local -r dst_file="${@: -1}" # get the last arg
    local -r temp_dst_file=$(mktemp "${dst_file}.XXXXXXXX")

    # ${@:1:N} is to get the sub array of 1st...Nth elements of $@
    # $(($#-1)) is $# - 1
    # ${@:1:$(($#-1))} is to get sub array of $@ without the last arg
    jq "${@:1:$(($#-1))}" > "${temp_dst_file}"
    mv "${temp_dst_file}" "${dst_file}"
}

regen_domain_hash()
{
    local SMB_PRIVATE="$1"
    local SYNOADS_CONF_HASH="${SMB_PRIVATE}/$2"

    if [[ ! -s "${SMB_PRIVATE}/secrets.ldb" ]]; then
        exit 1
    fi
    realm=""
    workgroup=""
    hostname=""
    ldbresult=$(ldbsearch -H "${SMB_PRIVATE}/secrets.ldb" \
        '(objectClass=primaryDomain)' realm samAccountName flatname)

    # DON'T use `process substitution` here because upstart doesn't suppport it
    while IFS= read -r line; do
        case "${line,,}" in
            realm:*)
                realm=$(awk '{print $2}' <<< "${line}")
                ;;
            flatname:*)
                workgroup=$(awk '{print $2}' <<< "${line}")
                ;;
            samaccountname:*)
                hostname=$(awk '{print $2}' <<< "${line}")
                hostname=${hostname%$} # remove the latest $
                ;;
        esac
    done <<< "${ldbresult}"
    if [[ -z "${realm}" || -z "${workgroup}" || -z "${hostname}" ]]; then
        logger -p user.err "failed to regen domain hash, realm: '${realm}', workgroup: '${workgroup}', netbios_name: '${hostname}'"
        exit 1
    fi

    _safe_jq2file "." "${SYNOADS_CONF_HASH}" <<EOF
{
    "realm": "${realm,,}",
    "realm_upper": "${realm^^}",
    "workgroup": "${workgroup,,}",
    "workgroup_upper": "${workgroup^^}",
    "hostname": "${hostname,,}",
    "hostname_upper": "${hostname^^}"
}
EOF

}

if [ $# -lt 2 ]; then
    exit 1
fi

regen_domain_hash "$1" "$2"

# vim: set ft=sh expandtab shiftwidth=4 tabstop=4: