#!/bin/sh
# Clawdie operator USB resolver guard.
#
# FreeBSD installer-derived memsticks may leave /etc/resolv.conf pointing at
# /tmp/bsdinstall_etc/resolv.conf. On this live USB /tmp is tmpfs, so that
# target disappears at boot and DNS breaks even when DHCP, link, and routing
# are otherwise healthy. Repair only missing or installer-scratch resolver
# files; leave a valid operator/DHCP-managed resolver untouched.

# PROVIDE: clawdie_live_resolver
# REQUIRE: FILESYSTEMS
# BEFORE: netif NETWORKING avahi_daemon
# KEYWORD: nojail

. /etc/rc.subr

name="clawdie_live_resolver"
rcvar="${name}_enable"
start_cmd="${name}_start"
stop_cmd=":"

clawdie_live_resolver_recreate() {
    rm -f /etc/resolv.conf
    {
        echo "# Created by clawdie_live_resolver."
        echo "# DHCP/NetworkMgr may replace this file after interfaces come up."
    } >/etc/resolv.conf
    chmod 0644 /etc/resolv.conf
}

clawdie_live_resolver_start() {
    _target=""
    if [ -L /etc/resolv.conf ]; then
        _target="$(readlink /etc/resolv.conf 2>/dev/null || true)"
        case "$_target" in
            /tmp/bsdinstall_etc/*)
                echo "${name}: replacing installer resolver symlink ${_target}"
                clawdie_live_resolver_recreate
                return 0
                ;;
            *)
                if [ ! -e /etc/resolv.conf ]; then
                    echo "${name}: replacing dangling resolver symlink ${_target}"
                    clawdie_live_resolver_recreate
                fi
                return 0
                ;;
        esac
    fi

    if [ ! -e /etc/resolv.conf ]; then
        echo "${name}: creating missing /etc/resolv.conf"
        clawdie_live_resolver_recreate
    fi
}

load_rc_config "$name"
: "${clawdie_live_resolver_enable:=YES}"
run_rc_command "$1"
