#!/usr/bin/env bash
set -euo pipefail

kitty_config_dir="${XDG_CONFIG_HOME:-$HOME/.config}/kitty"
config_file="$kitty_config_dir/kitty.conf"
theme_file="$kitty_config_dir/themes/noctalia.conf"
include_line='include themes/noctalia.conf'

mkdir -p "$kitty_config_dir"
touch "$config_file"

tmp_file="$(mktemp "${config_file}.tmp.XXXXXX")"

cleanup() {
    rm -f "$tmp_file"
}
trap cleanup EXIT

awk -v include_line="$include_line" '
    # Remove the block generated by `kitty +kitten themes`.
    /^# BEGIN_KITTY_THEME[[:space:]]*$/ {
        in_theme_block = 1
        changed = 1
        next
    }

    in_theme_block && /^# END_KITTY_THEME[[:space:]]*$/ {
        in_theme_block = 0
        next
    }

    in_theme_block {
        next
    }

    # Preserve the first existing include exactly where it is.
    # Remove only duplicate copies.
    $0 == include_line {
        if (include_seen) {
            changed = 1
            next
        }

        include_seen = 1
        print
        next
    }

    {
        print
    }

    END {
        # Add the include only if it did not already exist.
        if (!include_seen) {
            print include_line
        }
    }
' "$config_file" >"$tmp_file"

# Replace kitty.conf only if its contents actually changed. Write through a symlink
# instead of replacing it with a regular file via mv.
if ! cmp -s "$config_file" "$tmp_file"; then
    cat "$tmp_file" >"$config_file"
fi

if [[ ! -f "$theme_file" ]]; then
    printf 'Warning: Kitty theme file not found: %s\n' "$theme_file" >&2
fi

# Reload all running Kitty instances.
pkill -USR1 kitty >/dev/null 2>&1 || true
