#!/bin/sh
set -e

# This code was taken from libnss-myhostname
remove_nss_entry() {
    refcount=$(dpkg-query -f '${db:Status-Abbrev} ${binary:Package}\n' \
        -W libnss-resolve | grep '^i' | wc -l)
    if [ "$refcount" -gt 0 ] ; then
        # there are other instances, do nothing
        return
    fi
    echo "Checking NSS setup..."
    # abort if /etc/nsswitch.conf does not exist
    if ! [ -e /etc/nsswitch.conf ]; then
        echo "Could not find /etc/nsswitch.conf."
        return
    fi
    perl -i -pe '
        sub remove {
            my $s=shift;
            $s=~s/\s+resolve\b//g;
            return $s;
        }
        s/^(hosts:)(.*)/$1.remove($2)/e;
    ' /etc/nsswitch.conf
}

if [ "$1" = remove ]; then
    remove_nss_entry
    systemctl disable systemd-resolved.service
    if [ -d /run/systemd/system ]; then
        deb-systemd-invoke stop systemd-resolved.service || true
    fi
fi


