#!/bin/sh
set -eu

STATE_DIR="/var/run/wireguard/resolvconf"
BACKUP_FILE="${STATE_DIR}/resolv.conf.backup"

mkdir -p "${STATE_DIR}"

if [ "$#" -eq 0 ]; then
    exit 0
fi

command="$1"
shift || true

restore_backup() {
    if [ -f "${BACKUP_FILE}" ]; then
        cat "${BACKUP_FILE}" > /etc/resolv.conf
    fi
}

apply_dns() {
    iface="$1"
    shift || true

    # Skip optional arguments such as -m <metric> or -x
    while [ "$#" -gt 0 ]; do
        case "$1" in
            -m|-p|-w)
                shift 2 || true
                ;;
            -x|-y|-Z)
                shift 1 || true
                ;;
            --)
                shift
                break
                ;;
            *)
                break
                ;;
        esac
    done

    tmp_file="${STATE_DIR}/${iface}.conf"
    cat > "${tmp_file}"

    if [ ! -f "${BACKUP_FILE}" ]; then
        cp /etc/resolv.conf "${BACKUP_FILE}" 2>/dev/null || true
    fi

    {
        echo "# Generated by WireGuard add-on resolvconf shim"
        cat "${tmp_file}"
    } > /etc/resolv.conf
}

case "${command}" in
    -a)
        if [ "$#" -eq 0 ]; then
            exit 0
        fi
        apply_dns "$@"
        ;;
    -d)
        if [ "$#" -gt 0 ]; then
            rm -f "${STATE_DIR}/$1.conf"
        fi
        restore_backup
        ;;
    -u)
        latest_conf="$(find "${STATE_DIR}" -maxdepth 1 -type f -name '*.conf' -print | head -n 1 || true)"
        if [ -n "${latest_conf}" ] && [ -f "${latest_conf}" ]; then
            {
                echo "# Generated by WireGuard add-on resolvconf shim"
                cat "${latest_conf}"
            } > /etc/resolv.conf
        else
            restore_backup
        fi
        ;;
    *)
        # Treat other commands as successful no-ops to remain compatible with wg-quick.
        exit 0
        ;;
esac
