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

config_dir="${XDG_CONFIG_HOME:-$HOME/.config}"
config_file="$config_dir/alacritty/alacritty.toml"

# alacritty expands ~ in import paths; keep it tilde'd so the path stays portable.
if [[ "$config_dir" == "$HOME"/* ]]; then
    theme_path="~/${config_dir#"$HOME"/}/alacritty/themes/noctalia.toml"
else
    theme_path="$config_dir/alacritty/themes/noctalia.toml"
fi

mkdir -p "$(dirname "$config_file")"

write_if_changed() {
    local target="$1" tmp="$2"
    if [ ! -e "$target" ] && [ ! -L "$target" ]; then
        mv "$tmp" "$target"
        return
    fi
    if ! cmp -s "$target" "$tmp"; then
        cat "$tmp" >"$target"
    fi
    rm -f "$tmp"
}

if [ ! -f "$config_file" ]; then
    cat >"$config_file" <<EOF
[general]
import = [
    "$theme_path"
]
EOF
    exit 0
fi

tmp_file="$(mktemp "${config_file}.tmp.XXXXXX")"
trap 'rm -f "$tmp_file"' EXIT

if grep -q 'noctalia\.toml' "$config_file"; then
    sed -E 's|"themes/noctalia.toml"|"'"$theme_path"'"|g' "$config_file" >"$tmp_file"
elif grep -q '^\[general\]' "$config_file"; then
    if grep -q '^import\s*=' "$config_file"; then
        sed '/^import\s*=\s*\[/,/\]/{/\]/s|]|    "'"$theme_path"'",\n]|}' "$config_file" >"$tmp_file"
    else
        sed '/^\[general\]/a import = ["'"$theme_path"'"]' "$config_file" >"$tmp_file"
    fi
else
    sed '1i [general]\nimport = ["'"$theme_path"'"]\n' "$config_file" >"$tmp_file"
fi

trap - EXIT
write_if_changed "$config_file" "$tmp_file"
