#!/usr/bin/env bash

set -o pipefail

CHAIN="XIVO-BUS"
BUS_PORTS="4369,5671,5672,25672"
CUSTOM_ENV_FILE="/etc/docker/xivo/custom.env"
PG_HBA_FILE="/var/lib/postgresql/17/data/pg_hba.conf"
RULES_DIR="/var/lib/xivo-rabbitmq"
DB_RETRIES=60

usage() {
    echo "Usage: ${0##*/} [--restore]"
    echo "  without option: compute the bus access rules from the XiVO configuration, apply and save them"
    echo "  --restore: apply the saved bus access rules"
}

log() {
    local priority="${1}"; shift
    if [[ -t 2 ]]; then
        echo "$*" >&2
    else
        echo "<${priority}>$*" >&2
    fi
}

log_error() {
    log 3 "ERROR: $*"
}

log_warning() {
    log 4 "WARNING: $*"
}

rules_file() {
    local family="${1}"; shift
    echo "${RULES_DIR}/bus-firewall.${family}.rules"
}

query_asterisk_db() {
    sudo -u asterisk psql asterisk -tAc "$1"
}

wait_for_asterisk_db() {
    for _ in $(seq "${DB_RETRIES}"); do
        query_asterisk_db "SELECT 1" >/dev/null 2>&1 && return 0
        sleep 1
    done
    log_error "asterisk database unreachable, bus access rules left unchanged"
    return 1
}

xivocc_host() {
    query_asterisk_db "SELECT host FROM accesswebservice WHERE name='xivows' AND host <> ''"
}

mds_voip_ips() {
    query_asterisk_db "SELECT voip_ip FROM mediaserver WHERE voip_ip <> ''"
}

extra_allowed_sources() {
    grep "^RABBITMQ_ALLOWED_IPS=" "${CUSTOM_ENV_FILE}" 2>/dev/null | tail -n 1 | cut -d= -f2-
}

pg_hba_entries() {
    [[ -r "${PG_HBA_FILE}" ]] || return 0
    awk '$1 ~ /^host/ && $2 ~ /(^|,)(asterisk|all)(,|$)/ {print $4, $5}' "${PG_HBA_FILE}"
}

is_ipv4_source() {
    local source="${1}"; shift
    [[ "${source}" =~ ^([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})(/([0-9]{1,2}))?$ ]] || return 1
    local octet
    for octet in "${BASH_REMATCH[1]}" "${BASH_REMATCH[2]}" "${BASH_REMATCH[3]}" "${BASH_REMATCH[4]}"; do
        (( 10#${octet} <= 255 )) || return 1
    done
    [[ -z "${BASH_REMATCH[6]}" ]] || (( 10#${BASH_REMATCH[6]} <= 32 ))
}

is_ipv6_source() {
    local source="${1}"; shift
    [[ "${source}" =~ ^[0-9A-Fa-f:.]*:[0-9A-Fa-f:.]*(/([0-9]{1,3}))?$ ]] || return 1
    [[ -z "${BASH_REMATCH[2]}" ]] || (( 10#${BASH_REMATCH[2]} <= 128 ))
}

is_hostname() {
    local source="${1}"; shift
    [[ "${source}" =~ ^[A-Za-z0-9]([A-Za-z0-9.-]*[A-Za-z0-9])?$ && "${source}" =~ [A-Za-z] ]]
}

mask_to_prefix() {
    local mask="${1}"; shift
    local prefix=0 host_bits_started=0 octet
    local -a octets
    IFS=. read -r -a octets <<< "${mask}"
    [[ ${#octets[@]} -eq 4 ]] || return 1
    for octet in "${octets[@]}"; do
        if (( host_bits_started )); then
            [[ "${octet}" == 0 ]] || return 1
            continue
        fi
        case "${octet}" in
            255) prefix=$(( prefix + 8 )); continue;;
            254) prefix=$(( prefix + 7 ));;
            252) prefix=$(( prefix + 6 ));;
            248) prefix=$(( prefix + 5 ));;
            240) prefix=$(( prefix + 4 ));;
            224) prefix=$(( prefix + 3 ));;
            192) prefix=$(( prefix + 2 ));;
            128) prefix=$(( prefix + 1 ));;
            0) ;;
            *) return 1;;
        esac
        host_bits_started=1
    done
    echo "${prefix}"
}

print_normalized_source() {
    local source="${1}"; shift
    case "${source}" in
        127.*|::1|::1/128) return 0;;
        */0)
            log_warning "${source} would allow every host, skipped"
            return 0;;
    esac
    source="${source%/32}"
    echo "${source%/128}"
}

print_resolved_source() {
    local source="${1}"; shift
    if is_ipv4_source "${source}" || is_ipv6_source "${source}"; then
        print_normalized_source "${source}"
        return 0
    fi
    if ! is_hostname "${source}"; then
        log_error "invalid bus access source ${source}, skipped"
        return 0
    fi
    local addresses
    addresses=$(getent ahosts "${source}" | awk '{print $1}' | sort -u)
    if [[ -z "${addresses}" ]]; then
        log_error "cannot resolve bus access source ${source}, skipped"
        return 0
    fi
    local address
    for address in ${addresses}; do
        print_normalized_source "${address}"
    done
}

print_pg_hba_source() {
    local address="${1}"; shift
    local mask="${1}"; shift
    if is_ipv4_source "${address}" && [[ "${address}" != */* && "${mask}" == *.*.*.* ]]; then
        local prefix
        if ! prefix=$(mask_to_prefix "${mask}"); then
            log_warning "pg_hba.conf entry ${address} ${mask}: invalid mask, skipped"
            return 0
        fi
        address="${address}/${prefix}"
    fi
    if is_ipv4_source "${address}" || is_ipv6_source "${address}"; then
        print_normalized_source "${address}"
    else
        log_warning "pg_hba.conf entry ${address} is not an IP address or network, skipped"
    fi
}

collect_sources() {
    local cc_host mds_ips source address mask
    cc_host=$(xivocc_host) || return 1
    mds_ips=$(mds_voip_ips) || return 1
    for source in ${cc_host} ${mds_ips} $(extra_allowed_sources); do
        print_resolved_source "${source}"
    done
    while read -r address mask; do
        print_pg_hba_source "${address}" "${mask}"
    done < <(pg_hba_entries)
}

bus_chain_rules() {
    echo "*filter"
    echo ":${CHAIN} - [0:0]"
    echo "-A ${CHAIN} -i lo -j ACCEPT"
    echo "-A ${CHAIN} -i docker0 -j ACCEPT"
    echo "-A ${CHAIN} -i br-+ -j ACCEPT"
    local source
    for source in "$@"; do
        echo "-A ${CHAIN} -s ${source} -j ACCEPT"
    done
    echo "-A ${CHAIN} -j DROP"
    echo "COMMIT"
}

hook_chain_in_input() {
    local firewall_command="${1}"; shift
    local rule=(INPUT -p tcp -m multiport --dports "${BUS_PORTS}" -j "${CHAIN}")
    "${firewall_command}" -w -C "${rule[@]}" 2>/dev/null || "${firewall_command}" -w -I "${rule[@]}"
}

apply_rules() {
    local firewall_command="${1}"; shift
    "${firewall_command}-restore" --noflush -w && hook_chain_in_input "${firewall_command}"
}

ipv6_available() {
    command -v ip6tables-restore >/dev/null && [[ -e /proc/net/if_inet6 ]]
}

compute_family() {
    local firewall_command="${1}"; shift
    local family="${1}"; shift
    local file temporary_file
    file=$(rules_file "${family}")
    temporary_file="${file}.tmp"
    bus_chain_rules "$@" > "${temporary_file}" || return 1
    if ! apply_rules "${firewall_command}" < "${temporary_file}"; then
        rm -f "${temporary_file}"
        log_error "${family} bus access rules refused, previous rules left unchanged"
        return 1
    fi
    mv -f "${temporary_file}" "${file}"
    echo "${family} bus ports ${BUS_PORTS} restricted to local containers and: $*"
}

compute_rules() {
    wait_for_asterisk_db || return 1
    local sources
    if ! sources=$(collect_sources); then
        log_error "cannot read the bus access sources, bus access rules left unchanged"
        return 1
    fi
    local -a ipv4_sources ipv6_sources
    mapfile -t ipv4_sources < <(awk 'NF && !/:/' <<< "${sources}" | sort -u)
    mapfile -t ipv6_sources < <(awk 'NF && /:/' <<< "${sources}" | sort -u)
    mkdir -p "${RULES_DIR}" || return 1
    local failed=0
    compute_family iptables ipv4 "${ipv4_sources[@]}" || failed=1
    if ipv6_available; then
        compute_family ip6tables ipv6 "${ipv6_sources[@]}" || failed=1
    else
        echo "IPv6 not available, IPv6 bus rules skipped"
    fi
    return "${failed}"
}

restore_family() {
    local firewall_command="${1}"; shift
    local family="${1}"; shift
    local file
    file=$(rules_file "${family}")
    if [[ -r "${file}" ]]; then
        if ! apply_rules "${firewall_command}" < "${file}"; then
            log_error "saved ${family} bus access rules ${file} refused"
            return 1
        fi
        echo "${family} bus access rules restored from ${file}"
        return 0
    fi
    log_warning "no saved ${family} bus access rules, bus ports not filtered until xivo-bus-firewall is run"
}

restore_rules() {
    local failed=0
    restore_family iptables ipv4 || failed=1
    if ipv6_available; then
        restore_family ip6tables ipv6 || failed=1
    else
        echo "IPv6 not available, IPv6 bus rules skipped"
    fi
    return "${failed}"
}

case "${1:-}" in
    "") compute_rules;;
    --restore) restore_rules;;
    -h|--help) usage;;
    *)
        usage >&2
        exit 1;;
esac
