#!/bin/bash

#
# Title: i3-config-builder
# Version: 0.1.0
# Author: dabruh
# GitLab: https://gitlab.com/dabruh
# GitHub: https://github.com/dabruh
#
# Builds an i3/i3status configuration file by merging
# multiple defined configurations in an orderly manner.
#
# The files you wish to include MUST exist under ~/.config/i3(status)/layers.
# The files MUST start with one of the defined "PATTERNS" below. However, they
# WILL NOT be read unless explicitly mentioned in a .layer file located in the
# same directory.
#
# Two .layer files are read during execution:
# - default.layer
# - $HOSTNAME.layer: This file doesn't have to exist, but will allow you to
#   load a special set of files depending on the hostname of the machine which
#   executes this script.
#
# The contents of the .layer files are read first, and then sorted.
#

HOSTNAME="$(hostname | cut -d. -f1)"
PATTERNS=(
    "config.vars"
    "config.pre-main"
    "config.main"
    "config.post-main"
)

function i3setup() {
    local file dir layers config includes path component="$1"
    dir="$HOME/.config/$component"
    layers="$dir/layers"
    config="$dir/config"

    echo "Building $component config... 🔨"
    rm "$config" 2>/dev/null
    includes=$(cat "$layers/default.layer" "$layers/$HOSTNAME.layer" 2>/dev/null | sort -u)

    for pattern in "${PATTERNS[@]}"; do
        for file in $includes; do
            ! [[ "$file" =~ "$pattern"* ]] && continue
            path="$layers/$file"

            if ! [ -f "$path" ] && ! [ -L "$path" ]; then
                echo "ERROR: Invalid path: $path"
                continue
            fi

            echo "WRITE : '$file'."
            {
                echo "# >>>$file"
                cat "$path"
                echo "# <<<$file"
                echo
            } >>"$config"
        done
    done
    echo
}

i3setup i3
i3setup i3status

echo "Restarting i3... 🔄"
i3 restart
