#!/bin/bash
# ==============================================================================
# Papers Library Setup Script
# Sets up symlinks for the bibliography/papers system
#
# Usage:
#   1. Clone the repo: git clone https://github.com/krisyotam/papers ~/dev/papers
#   2. Run this script: ~/dev/papers/setup.sh
#
# This creates:
#   ~/bib-lib -> ~/dev/papers (symlink)
#   ~/notes/references -> ~/dev/papers/roam/references (symlink)
# ==============================================================================

set -e

PAPERS_DIR="$HOME/dev/papers"
BIB_LINK="$HOME/bib-lib"
NOTES_DIR="$HOME/notes"
REFS_LINK="$NOTES_DIR/references"

echo "=== Papers Library Setup ==="
echo ""

# Check if papers repo exists
if [ ! -d "$PAPERS_DIR" ]; then
    echo "ERROR: Papers repo not found at $PAPERS_DIR"
    echo "Clone it first: git clone https://github.com/krisyotam/papers ~/dev/papers"
    exit 1
fi

# Handle ~/bib-lib
if [ -L "$BIB_LINK" ]; then
    echo "~/bib-lib is already a symlink, removing..."
    rm "$BIB_LINK"
elif [ -d "$BIB_LINK" ]; then
    echo "~/bib-lib is a directory, backing up to ~/bib-lib.bak..."
    if [ -d "$BIB_LINK.bak" ]; then
        rm -rf "$BIB_LINK.bak"
    fi
    mv "$BIB_LINK" "$BIB_LINK.bak"
fi

echo "Creating symlink: ~/bib-lib -> ~/dev/papers"
ln -sf "$PAPERS_DIR" "$BIB_LINK"

# Handle ~/notes/references
mkdir -p "$NOTES_DIR"

if [ -L "$REFS_LINK" ]; then
    echo "~/notes/references is already a symlink, removing..."
    rm "$REFS_LINK"
elif [ -d "$REFS_LINK" ]; then
    echo "~/notes/references is a directory, backing up..."
    if [ -d "$REFS_LINK.bak" ]; then
        rm -rf "$REFS_LINK.bak"
    fi
    mv "$REFS_LINK" "$REFS_LINK.bak"
fi

echo "Creating symlink: ~/notes/references -> ~/dev/papers/roam/references"
ln -sf "$PAPERS_DIR/roam/references" "$REFS_LINK"

echo ""
echo "=== Setup Complete ==="
echo ""
echo "Directory structure:"
echo "  ~/bib-lib -> ~/dev/papers"
echo "  ~/bib-lib/library.bib      - Main bibliography"
echo "  ~/bib-lib/temp-lib.bib     - Temporary imports"
echo "  ~/bib-lib/pdfs/            - Main PDF storage"
echo "  ~/bib-lib/temp-pdfs/       - Temporary PDFs"
echo "  ~/notes/references -> ~/dev/papers/roam/references"
echo ""
echo "Emacs config expects ~/bib-lib/ paths - these now point to ~/dev/papers"
echo ""
echo "To commit changes to your papers:"
echo "  cd ~/dev/papers && git add -A && git commit -m 'Update papers' && git push"
