#!/usr/bin/env bash
# dot-add: Move config files/dirs into the dotfiles repo and stow them.
#
# Usage: dot-add <package> <path> [<path> ...]
#
# Examples:
#   dot-add sway ~/.config/sway/config
#   dot-add sway ~/.config/sway/
#   dot-add sway ~/.config/sway/*

set -euo pipefail

DOTFILES_DIR="$(cd "$(dirname "$(readlink -f "$0")")" && pwd)"

if [[ $# -lt 2 ]]; then
  echo "Usage: dot-add <package> <path> [<path> ...]"
  exit 1
fi

PACKAGE="$1"
shift

MOVED_PARENTS=()

add_one() {
  local FILE
  FILE="$(realpath "$1")"

  if [[ ! -e "$FILE" ]]; then
    echo "Error: '$FILE' does not exist" >&2
    return 1
  fi

  if [[ ! "$FILE" == "$HOME/"* ]]; then
    echo "Error: '$FILE' is not under \$HOME" >&2
    return 1
  fi

  # Prevent adding files that are already inside the dotfiles repo
  if [[ "$FILE" == "$DOTFILES_DIR/"* ]]; then
    echo "Error: '$1' resolves into the dotfiles repo (via symlink?) — skipping" >&2
    return 1
  fi

  local REL="${FILE#$HOME/}"
  local DEST="$DOTFILES_DIR/$PACKAGE/$REL"

  # If the path is a git repo, add it as a submodule instead of moving files
  if [[ -d "$FILE/.git" ]]; then
    local REMOTE
    REMOTE="$(git -C "$FILE" remote get-url origin 2>/dev/null || true)"
    if [[ -z "$REMOTE" ]]; then
      echo "Error: '$FILE' is a git repo but has no remote origin — can't add as submodule" >&2
      return 1
    fi
    mkdir -p "$(dirname "$DEST")"
    rm -rf "$FILE"
    git -C "$DOTFILES_DIR" submodule add "$REMOTE" "$PACKAGE/$REL"
    echo "Added submodule: $REMOTE -> $DEST"
    return 0
  fi

  mkdir -p "$(dirname "$DEST")"
  mv "$FILE" "$DEST"
  echo "Moved: $FILE -> $DEST"
  MOVED_PARENTS+=("$(dirname "$FILE")")
}

for PATH_ARG in "$@"; do
  add_one "$PATH_ARG"
done

# Remove any empty source directories so stow can create clean symlinks
for dir in "${MOVED_PARENTS[@]}"; do
  if [[ -d "$dir" && -z "$(ls -A "$dir")" ]]; then
    rmdir "$dir"
  fi
done

stow --dir="$DOTFILES_DIR" --target="$HOME" --restow "$PACKAGE"
echo "Stowed: $PACKAGE"
