#!/bin/bash

# Script to switch the alacritty theme between rose-pine and rose-pine-dawn
#
# ./rose_pine_switch

set -euo pipefail

case "$(uname -s)" in
    Linux*)
        sed_i() { sed -i "$@"; }
        ;;
    Darwin*)
        sed_i() { sed -i '' "$@"; }
        ;;
    *)
        echo "Unknown platform"
        return 1
        ;;
esac

function switch_alacritty_colors() {
    local config_file
    config_file="$DOTFILES/alacritty/.config/alacritty/alacritty.toml"
    if ! grep -q 'colors' "$config_file"; then
        echo "Error, could not find import from colors directory"
        return 1
    fi
    if grep -q 'dawn' "$config_file"; then
        sed_i 's/rose-pine-dawn\.toml/rose-pine.toml/g' "$config_file"
    else
        sed_i 's/rose-pine\.toml/rose-pine-dawn.toml/g' "$config_file"
    fi
}

function switch_tmux_colors() {
    local config_file
    config_file="$DOTFILES/tmux/.tmux.conf"
    if ! grep -q 'rose_pine_variant' "$config_file"; then
        echo "Error, could not find rose pine settings in config file"
        return 1
    fi
    if grep -q '@rose_pine_variant '\''dawn'\''' "$config_file"; then
        sed_i 's/rose_pine_variant '\''dawn'\''/rose_pine_variant '\''main'\''/g' "$config_file"
        tmux source-file ~/.tmux.conf
    else
        sed_i 's/rose_pine_variant '\''main'\''/rose_pine_variant '\''dawn'\''/g' "$config_file"
        tmux source-file ~/.tmux.conf
    fi
}

function switch_k9s_colors() {
    local config_file
    config_file="$DOTFILES/k9s/.config/k9s/config.yaml"
    if ! grep -q 'rose-pine' "$config_file"; then
        echo "Error, could not find rose pine settings in config file"
        return 1
    fi
    if grep -q 'rose-pine-dawn' "$config_file"; then
        sed_i 's/rose-pine-dawn/rose-pine/g' "$config_file"
    else
        sed_i 's/rose-pine/rose-pine-dawn/g' "$config_file"
    fi
}

function switch_colors() {
    # Only work if the DOTFILES variable is set
    if [ -n "$DOTFILES" ]; then
        switch_alacritty_colors
        switch_tmux_colors
        switch_k9s_colors
    fi
}

switch_colors
