_fix_conf() {
    local conf=/etc/conf.d/distccd
    if [ -f "$conf" ] && grep -q '^DISTCC_ARGS=' "$conf"; then
        cp -a "$conf" "${conf}.pre-distcc-avahi-fix.$(date +%Y%m%d-%H%M%S)"
        sed -i 's/^DISTCC_ARGS=/DISTCC_OPTS=/' "$conf"
        echo "==> distcc-avahi: renamed DISTCC_ARGS -> DISTCC_OPTS in $conf"
        echo "    (the systemd unit reads \$DISTCC_OPTS; backup left as ${conf}.pre-distcc-avahi-fix.*)"
    fi
}

_clean_legacy_symlinks() {
    # Versions <= 3.4-18 shipped no symlinks in the package and instead ran
    # /usr/sbin/update-distcc-symlinks at .install time, leaving untracked
    # files at /usr/lib/distcc/<compiler>. Remove those so pacman can drop
    # the now-tracked symlinks in their place without a file conflict.
    local d=/usr/lib/distcc
    [ -d "$d" ] || return 0
    local f
    for f in "$d"/*; do
        [ -L "$f" ] || continue
        case "$(readlink "$f")" in
            ../../bin/distcc) rm -f "$f" ;;
        esac
    done
}

post_install() {
    _fix_conf
}

pre_upgrade() {
    _clean_legacy_symlinks
}

post_upgrade() {
    _fix_conf
    if systemctl is-active --quiet distccd 2>/dev/null; then
        echo "==> distcc-avahi: distccd.service is active; restart with"
        echo "    'sudo systemctl restart distccd' to pick up any conf change"
    fi
}
