#!/bin/sh

set -e
LIGHTTHEME="papertheme"
DARKTHEME="campbell"
VIMCONF="${XDG_CONFIG_HOME}/nvim/lua/basic.lua"
ALACRITTYCONF="${XDG_CONFIG_HOME}/alacritty/alacritty.toml"
TMUXCONF="${XDG_CONFIG_HOME}/tmux/tmux.conf"

export $(tmux show-env | grep THEME)

send_vim_cmd() {
    vims=$(tmux list-panes -a -F '#{pane_id} #{pane_current_command}' |
                    grep vim |
                    cut -d ' ' -f 1)
    for pane in $vims; do
        #echo "Sending command to '$pane' '$1'"
        tmux send-keys -t "$pane" ESCAPE "$1" ENTER
    done
}


if [ "$THEME" = "dark" ]; then
    # Update alacritty
    sed -i "s/${DARKTHEME}/${LIGHTTHEME}/" "${ALACRITTYCONF}"
    
    # Update tmux (Consider making a theme switch in the m4 config and re-running that instead of having it configured here)
    tmux set-environment THEME "light"
    tmux set-environment ALACRITTY_THEME "${LIGHTTHEME}"
    tmux set -g status-style "fg=colour255,bold,bg=black"

    # Update nvim
    send_vim_cmd ":set background=light"
    send_vim_cmd ":lua vim.api.nvim_set_hl(0, 'ColorColumn', { ctermbg = 'lightgrey', bg = '#eae7da' })"
    sed -i 's/"dark"/"light"/' "${VIMCONF}"
    sed -i 's/{ ctermbg = "lightgrey", bg = "#363636" }/{ ctermbg = "lightgrey", bg = "#eae7da" }/' "${VIMCONF}"

else
    # Update alacritty
    sed -i "s/${LIGHTTHEME}/${DARKTHEME}/" "${ALACRITTYCONF}"

    # Update tmux
    tmux set-environment THEME "dark"
    tmux set-environment ALACRITTY_THEME "${DARKTHEME}"
    tmux set -g status-style "fg=black,bg=white"

    # Update nvim
    send_vim_cmd ":set background=dark"
    send_vim_cmd ":lua vim.api.nvim_set_hl(0, 'ColorColumn', { ctermbg = 'lightgrey', bg = '#363636' })"
    sed -i 's/"light"/"dark"/' "${VIMCONF}"
    sed -i 's/{ ctermbg = "lightgrey", bg = "#eae7da" }/{ ctermbg = "lightgrey", bg = "#363636" }/' "${VIMCONF}"

fi
