#!/bin/bash

# Script to perform a hard reset to latest git version
# Usage: ./git_reset.sh [directory] [branch_name]
# Example: ./git_reset.sh /var/www/myapp main
# If no branch is specified, it will use 'main' as default
# If no directory is specified, it will use current directory

# Exit on any error
set -e

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Parse arguments
TARGET_DIR=${1:-.}
BRANCH=${2:-main}

# Log function
log() {
    echo -e "${GREEN}[$(date +'%Y-%m-%d %H:%M:%S')] $1${NC}"
}

error() {
    echo -e "${RED}[ERROR] $1${NC}" >&2
}

warning() {
    echo -e "${YELLOW}[WARNING] $1${NC}"
}

# Validate and navigate to target directory
if [ ! -d "$TARGET_DIR" ]; then
    error "Directory does not exist: $TARGET_DIR"
    exit 1
fi

# Convert to absolute path
TARGET_DIR=$(cd "$TARGET_DIR" && pwd)
log "Target directory: $TARGET_DIR"

# Navigate to target directory
cd "$TARGET_DIR"

# Check if we're in a git repository
if ! git rev-parse --is-inside-work-tree > /dev/null 2>&1; then
    error "Not a git repository: $TARGET_DIR"
    exit 1
fi

# Store current branch name
CURRENT_BRANCH=$(git symbolic-ref --short HEAD)

# Create backup of current state
BACKUP_DIR="$TARGET_DIR/git_backup_$(date +'%Y%m%d_%H%M%S')"
log "Creating backup directory: $BACKUP_DIR"
mkdir -p "$BACKUP_DIR"

# Backup uncommitted changes
if [[ -n $(git status -s) ]]; then
    warning "Uncommitted changes found. Creating backup..."
    git diff > "$BACKUP_DIR/uncommitted_changes.patch"
    git status > "$BACKUP_DIR/git_status.txt"
fi

# Backup current branch information
git rev-parse HEAD > "$BACKUP_DIR/current_commit.txt"
git branch > "$BACKUP_DIR/branches.txt"

log "Fetching latest changes from remote..."
git fetch --all

log "Checking out branch: $BRANCH"
if ! git checkout "$BRANCH"; then
    error "Failed to checkout branch: $BRANCH"
    exit 1
fi

log "Resetting to latest remote version..."
if ! git reset --hard "origin/$BRANCH"; then
    error "Failed to reset to origin/$BRANCH"
    exit 1
fi

log "Cleaning untracked files and directories..."
git clean -fd

# Pull latest changes
log "Pulling latest changes..."
git pull origin "$BRANCH"

# Final status check
if [ $? -eq 0 ]; then
    log "Successfully reset to latest version of $BRANCH"
    log "Backup saved in: $BACKUP_DIR"
    log "Current git status:"
    git status
    
    # Print summary
    echo -e "\n${GREEN}=== Reset Summary ===${NC}"
    echo -e "Directory: $TARGET_DIR"
    echo -e "Branch: $BRANCH"
    echo -e "Backup Location: $BACKUP_DIR"
    echo -e "Current Commit: $(git rev-parse --short HEAD)"
else
    error "Something went wrong during the reset process"
    error "Check the backup in: $BACKUP_DIR"
    exit 1
fi 