#!/bin/sh

set -eu

config_dir=${1:-"$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)"}

for appearance in dark light no-preference; do
    config_file="$config_dir/$appearance-theme.auto.conf"
    [ -f "$config_file" ] || continue

    if awk '
        $1 == "macos_titlebar_color" {
            count++
            if ($2 == "background") correct++
        }
        END { exit !(count == 1 && correct == 1) }
    ' "$config_file"; then
        continue
    fi

    tmp=$(mktemp "$config_file.tmp.XXXXXX")
    trap 'rm -f "$tmp"' EXIT HUP INT TERM
    awk '$1 != "macos_titlebar_color"' "$config_file" > "$tmp"
    printf '\nmacos_titlebar_color background\n' >> "$tmp"
    chmod "$(stat -f '%Lp' "$config_file")" "$tmp"
    mv -f "$tmp" "$config_file"
    trap - EXIT HUP INT TERM
done
