#!/usr/bin/env bash
# dot-remove: Unstow a package and move its files back to their original locations.
#
# Usage: dot-remove <package>
#
# Example: dot-remove oh-my-zsh

set -euo pipefail

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

if [[ $# -ne 1 ]]; then
  echo "Usage: dot-remove <package>"
  exit 1
fi

PACKAGE="$1"
PACKAGE_DIR="$DOTFILES_DIR/$PACKAGE"

if [[ ! -d "$PACKAGE_DIR" ]]; then
  echo "Error: package '$PACKAGE' not found in $DOTFILES_DIR"
  exit 1
fi

# Remove symlinks first
stow --dir="$DOTFILES_DIR" --target="$HOME" --delete "$PACKAGE"
echo "Unstowed: $PACKAGE"

# Move files back to their original locations
while IFS= read -r -d '' FILE; do
  REL="${FILE#$PACKAGE_DIR/}"
  DEST="$HOME/$REL"
  mkdir -p "$(dirname "$DEST")"
  mv "$FILE" "$DEST"
  echo "Restored: $DEST"
done < <(find "$PACKAGE_DIR" -type f -print0)

# Remove now-empty package directory
rm -rf "$PACKAGE_DIR"
echo "Removed: $PACKAGE_DIR"
echo ""
echo "Next steps:"
echo "  cd ~/dotfiles"
echo "  git rm -r $PACKAGE"
echo "  git commit -m 'remove $PACKAGE'"
