#!/usr/bin/env bash
# Load our configuration files
# Copyright (c) 2023 Ismo Vuorinen. All Rights Reserved.

DOTFILES="${DOTFILES:-$HOME/.dotfiles}"

source "$DOTFILES/config/shared.sh"

# Enable verbosity with VERBOSE=1 x-load-configs
VERBOSE="${VERBOSE:-0}"
# Enable debugging with DEBUG=1 x-load-configs
DEBUG="${DEBUG:-0}"

# Get the hostname
CONFIG_HOST="$(hostname -s)"

# Enable debugging if requested
[ "$DEBUG" = "1" ] && set -x

CONFIG_PATH="${HOME}/.config"

[ -d "$DOTFILES" ] || {
  msg_err "Error: DOTFILES is not set or $DOTFILES does not exist"
}

# Function to print messages if VERBOSE is enabled
# $1 - message type (string)
# $2 - message content (string)
config_msg()
{
  # if $1 is empty, return
  [ -z "$1" ] && return
  [ -z "$2" ] && $2=""

  local msg_type="$1"
  local msg_content="$2"
  [[ "$VERBOSE" -eq 1 ]] && printf 'x-load-configs: %s %s\n' "$msg_type" "$msg_content"
  return 0
}

# Function to get the full path of a config file
# $1 - filename (string)
config_file_path()
{
  echo "$CONFIG_PATH/$1"
}

# Function to source configuration files
source_config()
{
  local config_file=$1
  if [ -f "$config_file" ]; then
    eval "$config_file"
    config_msg "Sourced" "$config_file"
  else
    msg "Config file $config_file not found"
  fi
  return 0
}

# Function to load a configuration file
# $1 - base config file name (string)
load_config_files()
{
  local config_file="$1"
  local secret_file="${config_file}-secret"
  local host_file="${config_file}-${CONFIG_HOST}"
  local secret_host_file="${host_file}-secret"

  config_msg "Looking for" "$config_file"
  [ -r "$config_file" ] && {
    source_config "$config_file"
  }

  config_msg "Looking for" "$secret_file"
  [ -r "$secret_file" ] && {
    source_config "$secret_file"
  }

  config_msg "Looking for" "$host_file"
  [ -r "$host_file" ] && {
    source_config "$host_file"
  }

  config_msg "Looking for" "$secret_host_file"
  [ -r "$secret_host_file" ] && {
    source_config "$secret_host_file"
  }
  return 0
}

config_msg "VERBOSE=1" "Verbose mode enabled"
config_msg "HOST" "$CONFIG_HOST"

load_config_files "$(config_file_path "exports")"
load_config_files "$(config_file_path "alias")"
exit 0
