#!/bin/bash

LOCAL="$1"
REMOTE="$2"
BASE="$3"
MERGED="$4"
BACKUP="/tmp/$(date +"%Y%d%m%H%M%S")"

# Sanitize LOCAL path
if [[ ! "$LOCAL" =~ ^/ ]]; then
    LOCAL=$(echo "$LOCAL" | sed -e 's/^\.\///')
    LOCAL="$PWD/$LOCAL"
fi

# Sanitize REMOTE path
if [[ ! "$REMOTE" =~ ^/ ]]; then
    REMOTE=$(echo "$REMOTE" | sed -e 's/^\.\///')
    REMOTE="$PWD/$REMOTE"
fi

# If merging, sanitize BASE and MERGED paths
if [ -n "$MERGED" ]; then
    if [[ ! "$BASE" =~ ^/ ]]; then
        BASE=$(echo "$BASE" | sed -e 's/^\.\///')
        BASE="$PWD/$BASE"
        
        if [ ! -f "$BASE" ]; then
            BASE=/dev/null
        fi
    fi

    if [[ ! "$MERGED" =~ ^/ ]]; then
        MERGED=$(echo "$MERGED" | sed -e 's/^\.\///')
        MERGED="$PWD/$MERGED"

        if [ ! -f "$MERGED" ]; then
            # For conflicts, try to find a corresponding file
            MERGED=$(echo "$LOCAL" | sed -e 's/\.LOCAL\.[0-9]*//')
        fi
    fi
fi

# Check if Visual Studio Code is installed and locate the `code` command
VS_CODE_PATH="/Applications/Visual Studio Code.app/Contents/Resources/app/bin/code"

if [ ! -x "$VS_CODE_PATH" ]; then
    echo "Visual Studio Code is not installed or the 'code' command is not found. Please make sure you have VSCode installed and the command line tools are properly set up." >&2
    exit 128
fi

# Perform the diff or merge operation
if [ -n "$MERGED" ]; then
    # If merging, run VSCode in merge mode
    sleep 1  # Sleep to ensure timestamps are different
    touch "$BACKUP"

    "$VS_CODE_PATH" --wait --merge "$LOCAL" "$REMOTE" "$BASE" "$MERGED"
else
    # If not merging, run VSCode in diff mode
    "$VS_CODE_PATH" --wait --diff "$LOCAL" "$REMOTE"
fi

# If merging, check if the merged file has changed
if [ -n "$MERGED" ]; then
    if [ "$MERGED" -ot "$BACKUP" ]; then
        exit 1
    fi
fi

exit 0
