#!/bin/bash
# Samba CTDB configuration tool
# 注意这个脚本只编辑smb.conf，不管samba服务的启动与否

if [ "$RUNMODE" != "aa" ]; then
    echo "CTDB is only needed in active-active mode, skipping"
    exit 0
fi

FILE=/etc/samba/smb.conf
DATA_POOL_CFG="/unas/etc/dualcontroller/cfg/dualcontroller"
SMB_CTDB_LOCK="$DATA_POOL_CFG/run/ctdb.lock"

rm_ctdb() {
    # Ensure [global] section has clustering = yes and ctdbd socket
    if grep -q "\[global\]" "$FILE"; then
        # Use a temporary file to avoid partial writes
        tmpfile=$(mktemp)
        cp "$FILE" "$tmpfile"

        # Remove existing clustering/ctdbd lines if any (to avoid duplicates or conflicts)
        sed -i '/^[[:space:]]*clustering[[:space:]]*=/d' "$tmpfile"
        sed -i '/^[[:space:]]*ctdbd socket[[:space:]]*=/d' "$tmpfile"

        if ! diff "$FILE" "$tmpfile" > /dev/null; then
            cat "$tmpfile" > "$FILE"
        fi
        rm "$tmpfile"
    fi
}

add_ctdb() {
    # Ensure [global] section has clustering = yes and ctdbd socket
    if grep -q "\[global\]" "$FILE"; then
        # Use a temporary file to avoid partial writes
        tmpfile=$(mktemp)
        cp "$FILE" "$tmpfile"

        # Remove existing clustering/ctdbd lines if any (to avoid duplicates or conflicts)
        sed -i '/^[[:space:]]*clustering[[:space:]]*=/d' "$tmpfile"
        sed -i '/^[[:space:]]*ctdbd socket[[:space:]]*=/d' "$tmpfile"

        # Add them back under [global]
        # clustering = yes is essential for Samba to join CTDB
        # ctdbd socket defines where to talk to the CTDB daemon
        sed -i '/\[global\]/a \    clustering = yes\n    ctdbd socket = /var/run/ctdb/ctdbd.socket' "$tmpfile"

        if ! diff "$FILE" "$tmpfile" > /dev/null; then
            cat "$tmpfile" > "$FILE"
        fi
        rm "$tmpfile"
    fi
}

case "$1" in
    add)
        add_ctdb
        ;;
    remove)
        # Optionally remove the lock file on cleanup
        rm_ctdb
        ;;
    *)
        echo "Usage: $0 {add|remove}"
        exit 1
        ;;
esac
