#!/usr/bin/env fish
set --local to_provision $(
    join -v1 \
        (awk '
            /^[a-z]/ {
                gsub(/,/, "");
                gsub(/ {/, "");
                gsub(/[[:space:]]+/, "\n");
                if ($1 !~ /fly\.dev/) {
                    print
                }
            }
        ' Caddyfile | sort | psub) \
        (fly certs list --json | fx @.hostname list | sort | psub)
)

argparse n/dry-run -- $argv

if set --query to_provision[1]
    echo "Setup required for hostnames: $to_provision"
    echo

    if set --query _flag_dry_run
        exit
    end

    for name in $to_provision
        if test -z "(kdig +short TXT _fly-ownership.$name)"
            fly certs add $name
            fly certs remove --acme --yes $name
        else
            echo Add the hostname to DNS, then run
            echo fly certs add $name
            echo fly certs remove --acme --yes $name
        end

        echo
    end
end
