set positional-arguments := true

# Top-level PF anchor names are allowed to be anything, but reverse domain
# names seem to be preferred (MacOS uses com.apple by default), so I've
# followed that convention with my own domain.

anchor-name := "me.00dani.pf-dev"
anchor-pattern := replace(anchor-name, ".", "\\.")

# Display some basic info on how to use this project.
help:
    #!/bin/sh
    echo "Enter \`just load\` with the anchors you want to enable! Supported anchors are:"
    cd anchors
    for ANCHOR in *; do
        printf "%5s  %s\n" "$ANCHOR" "$(sed -n '2{s/^# //p;q;}' "$ANCHOR")"
    done
    grep -q '{{ anchor-pattern }}' /etc/pf.conf || {
        printf "\n%s\n" "You will also need to run \`just install\` (uses sudo) for initial setup."
    }

# Generate a parent anchor file that loads the child anchors of your choice. Example: just load dns http
load +ANCHORS:
    #!/bin/sh
    printf '%s\n%s\n' '# vim: set ft=pf :' '# This file was autogenerated! Call `just load` to create a fresh one.' > .load
    for ANCHOR; do
        [ -f "anchors/$ANCHOR" ] || {
            echo "Unknown anchor $ANCHOR!" >&2
            exit 1
        }
        printf '\nrdr-anchor "%s"\nload anchor "%s" from "%s/anchors/%s"\n' "$ANCHOR" "$ANCHOR" "$PWD" "$ANCHOR" >> .load
    done

# Globally install a modified pf.conf with pf-dev hooks added (will use sudo).
install: _generate-pf-conf _display-pf-conf _install-pf-conf

_generate-pf-conf:
    sed -En '/"{{ anchor-pattern }}"/d; p; /^([a-z]+-)?anchor "com\.apple/ s/".+"/"{{ anchor-name }}"/ p' /etc/pf.conf > pf.conf
    echo 'load anchor "{{ anchor-name }}" from "{{ justfile_directory() }}/.load"' >> pf.conf

[no-exit-message]
_display-pf-conf:
    #!/bin/sh
    echo "Generated a new pf.conf with pf-dev hooks included."
    diff -u --color=auto /etc/pf.conf pf.conf
    err=$?
    if [ $err -eq 0 ]; then
        echo "No changes need to be made to your pf.conf."
        rm pf.conf
        exit 1 # skip attempting to install
    fi
    if [ $err -gt 1 ]; then
        echo "Failed to diff the generated pf.conf against your current pf.conf."
        exit $err
    fi

[confirm("Are you happy to globally install the above pf.conf on your system?")]
_install-pf-conf:
    sudo cp pf.conf /etc/pf.conf
    rm pf.conf