#!/usr/bin/env bash

export dfp
export XDG_CONFIG_HOME="${XDG_CONFIG_HOME:-$HOME/.config}"
export ENV_PATH="$XDG_CONFIG_HOME/lytedev-env"
export CURDIR

mkdir -p "$ENV_PATH"
mkdir -p "$XDG_CONFIG_HOME"
dfp="$(realpath "$(dirname "$0")"/../..)"

# may not be running from inside the dotfiles repo, may have been curl'd down solo, so we need to check
if [[ ! -d "$dfp/.git" ]]; then
  echo "Not running from inside the dotfiles git repo, so we need to download it first!"
  # each os needs instructions to install git, then we can clone the repo and proceed
  if ! command -v git; then
    if head /etc/os-release --lines 1 | grep 'Arch Linux' > /dev/null 2>&1; then
      if [[ "$EUID" -ne 0 ]]; then
        if ! command -v sudo; then
          echo "Error: No sudo command available to try and install 'git'"
          exit 1
        else
          sudo pacman -Sy --needed git
        fi
      else
        pacman -Sy --needed git
      fi
    fi
  fi
  dfp="$XDG_CONFIG_HOME/lytedev-dotfiles"
  git clone https://git.lyte.dev/lytedev/dotfiles.git "$dfp"
fi

# auto-link any OS-specific environments
if head /etc/os-release --lines 1 | grep 'NixOS$' > /dev/null 2>&1; then
  ln -s "$dfp/os/linux/nix" "$ENV_PATH/os-linux-nix" > /dev/null 2>&1
elif head /etc/os-release --lines 1 | grep 'Arch Linux' > /dev/null 2>&1; then
  ln -s "$dfp/os/linux/arch" "$ENV_PATH/os-linux-arch" > /dev/null 2>&1
fi

# perform any pre-requisite setup (includes OS-specific setup scripts since we
# just included those)
for s in "$ENV_PATH"/*; do
  f="$s/dotfiles-init.d.sh"
  if [ -f "$f" ]; then
    echo "dotfiles-init: Running $f..."
    CURDIR="$s" "$f"
  fi
done

# perform final dotfiles setup
echo "dotfiles-init: Running setup..."
"$dfp/common/bin/dotfiles-setup"

# TODO: setup personal files? (ssh keys, gpg keys, password stores, notes)
# these are probably best handled in a dotfiles-init.d.sh script in a particular layer