#!/bin/bash

# Ensure correct arguments
if [ "$#" -ne 3 ]; then
    echo "Usage: $0 <cas-dir> <source-dir> <output-index-file>"
    exit 1
fi

CAS_DIR="$1"
SOURCE_DIR="$2"
INDEX_FILE="$3"

# Make sure the CAS directory exists
mkdir -p "$CAS_DIR"

# Clear the index file
> "$INDEX_FILE"

# Process all files in the source directory
find "$SOURCE_DIR" -type f | while read -r file; do
    # Compute the SHA256 hash of the file
    hash=$(sha256sum "$file" | awk '{print $1}')
    
    # Get relative path
    rel_path="${file#$SOURCE_DIR/}"

    # Determine file extension
    ext="${file##*.}"
    [ "$ext" != "$file" ] || ext=""  # Remove extension if none exists

    # Construct CAS storage path
    prefix="${hash:0:2}"
    cas_file="$CAS_DIR/$prefix/$hash"

    # Add extension if applicable
    if [ -n "$ext" ]; then
        cas_file="$cas_file.$ext"
    fi

    # Write the entry to the index file
    echo "$hash $rel_path" >> "$INDEX_FILE"

    # Check if the file is already in CAS and valid
    if [ -f "$cas_file" ] && sha256sum -c --quiet <(echo "$hash  $cas_file"); then
        echo "✅ Exists: $cas_file"
    else
        # Ensure the CAS directory exists
        mkdir -p "$CAS_DIR/$prefix"
        
        # Copy file to CAS
        cp "$file" "$cas_file"
        echo "🔄 Copied: $cas_file"
    fi
done

echo "✅ Index file written: $INDEX_FILE"
