#!/usr/bin/env bash
# Samba active directory provision
# Tool for provision samba active directory
#
# Copyright (C) 2024 Evgenii Sozonov <arzdez@altlinux.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

# shellcheck disable=SC2034
# shellcheck disable=SC1091
# shellcheck disable=SC2086
# shellcheck disable=SC2317
# shellcheck disable=SC3037

. shell-ini-config

set -euo pipefail

PATH_TO_ENTRY="/usr/share/alterator/services/service-samba-ad.service"

update_toml_field(){
    local section="$1"
    local key="$2"
    local value="$3"
    local file="${4:-$PATH_TO_ENTRY}"

    if [[ ! -f "$file" ]]; then
        echo "Error: File $file not found" >&2
        return 1
    fi

    ini_config_set "$file" "$section" "$key" "$value"
    sed -i 's/\t//g' "$file"
    sed -i '/^\['"$section"'\]/,/^\[/{s/^\(default\s*=\s*\)\([^"]\)/\1"\2/; s/^\(default\s*=\s*"[^"]*\)\([^"]\)$/\1\2"/}' "$file"
    return 0
}

update_realm(){
    local realm=
    local hostname=
    realm=$(hostname -d)
    hostname=$(hostname -s)

    if [ "$hostname" = "$realm" ]; then
        sed -i '/^\[parameters\.realm\]/,/^\[/{/^default\s*=/d}' "$PATH_TO_ENTRY"
        return 0
    fi

    update_toml_field "parameters.realm" "default" "$realm"
    return 0
}

update_hostname(){
    local hostname=
    hostname=$(hostname -s)

    update_toml_field "parameters.hostNetBiosName" "default" "$hostname"
    return 0
}

update_domain_netbios_name(){
    local domain_netbios_name=
    local hostname=
    domain_netbios_name=$(hostname -f | cut -d. -f2)
    hostname=$(hostname -s)
    if [ "$domain_netbios_name" = "$hostname" ]; then
        sed -i '/^\[parameters\.netBiosName\]/,/^\[/{/^default\s*=/d}' "$PATH_TO_ENTRY"
        return 0
    fi

    update_toml_field "parameters.netBiosName" "default" "$domain_netbios_name"
    return 0
}

update_entry(){
    update_realm
    update_hostname
    update_domain_netbios_name
    return 0
}
