#!/bin/bash

# Check if ~/.dotfiles exists
if [ ! -d "$HOME/.dotfiles" ]; then
    echo "Error: ~/.dotfiles directory does not exist."
    echo "Please clone your dotfiles repository to ~/.dotfiles first."
    exit 1
fi

cd ~/.dotfiles || exit 1
git pull
git submodule update --init --recursive
echo "Creating symbolic links for dotfiles..."

ignore_files=("dotfiles.sh" "README.md" ".git" ".gitignore")
backup_dir="$HOME/.dotfiles_backup/$(date +%Y%m%d_%H%M%S)"

# For each file/dir in the dotfiles directory
for file in $(ls -A); do
    # If the file is not in the ignore list
    if [[ ! " ${ignore_files[@]} " =~ " ${file} " ]]; then
        target="$HOME/$file"
        source="$PWD/$file"
        
        # Skip if it's already a correct symlink
        if [ -L "$target" ] && [ "$(readlink "$target")" = "$source" ]; then
            echo "✓ Symlink for $file already exists and is correct."
            continue
        fi
        
        # Backup existing file/directory if it exists
        if [ -e "$target" ]; then
            mkdir -p "$backup_dir"
            echo "⚠ Backing up existing $file to $backup_dir/"
            mv "$target" "$backup_dir/$file"
        fi
        
        # Create a symbolic link
        if [ -d "$source" ]; then
            echo "Creating symbolic link for directory: $file"
        else
            echo "Creating symbolic link for file: $file"
        fi
        
        if ln -s "$source" "$target"; then
            echo "✓ Successfully linked $file"
        else
            echo "✗ Failed to create symlink for $file"
        fi
    fi
done

echo "Dotfiles setup complete."