#!/usr/pkg/bin/bash
##   DO NOT EDIT. This is an auto-generated file.
##   Created on Sat Jul 19 17:16:14 UTC 2025

prefix="/usr/pkg"
pkgdatadir="${prefix}/share/git-sqlite"  # e.g. /usr/local/share/PACKAGE/

. "$pkgdatadir/util.sh"

ancestor="$1"
localDb="$2"
remote="$3"
marker="$4"
placeholder="$5"

#printErr "ancestor=$ancestor"
#printErr "localDb=$localDb"
#printErr "remote=$remote"
#printErr "marker=$marker"
#printErr "placeholder=$placeholder"

# get the diffs from the common ancestor to our states
ancestor2localDiff="$(diffDb "$ancestor" "$localDb")"
ancestor2remoteDiff="$(diffDb "$ancestor" "$remote")"

# backup the localDb before merging
backupDb="${localDb}.bak"
cp "$localDb" "$backupDb"

# apply each diff to its counterpart
sqlite3 "$localDb" "$ancestor2remoteDiff"
sqlite3 "$remote" "$ancestor2localDiff"

# diff our db's again
local2remote="$(diffDb "$localDb" "$remote" "--no-transaction")"
remote2local="$(diffDb "$remote" "$localDb" "--no-transaction")"

# get tmp files
local2remoteTmp="$(mktemp)"
remote2localTmp="$(mktemp)"

# add the contents
echo "$local2remote" > "$local2remoteTmp"
echo "$remote2local" > "$remote2localTmp"

# diff the tmp files
gitDiff="$(git diff --no-index "$local2remoteTmp" "$remote2localTmp")"

#printErr "gitDiff = $gitDiff"

formatGitDiff()
{
    # comment out header lines and diff ranges

    awk -v prefix="-- " '{ if( /^diff/ || /^index/ || /^@@/ || /^\+\+\+/ || /^---/ ) { print prefix $0 } else print $0 }' \
        | awk -v localMark="/*<LOCAL>*/" -v eol="/*</LOCAL>*/" '{ if ( /^-[^-]/ ) { print localMark substr($0,2) eol } else print $0 }' \
        | awk -v remoteMark="/*<REMOTE>*/ " -v eol="/*</REMOTE>*/" '{ if ( /^\+[^+]/ ) { print remoteMark substr($0,2) eol } else print $0 }' \
        | grep -v "^~$"

}

# throw a conflict warning if theres a diff still
if [ -n "$gitDiff" ]; then

    # format the diff for sql consumption
    fmtGitDiff="$(echo "$gitDiff" | formatGitDiff )"
    #printErr "fmtGitDiff = $fmtGitDiff"

    # echo it to an output file for manual editing
    conflictFile="${placeholder}-.merge_file.sql"
    echo "$fmtGitDiff" > "$conflictFile"

    # restore the backup
    mv "$backupDb" "$localDb"

    # exit the script
    exit 1

fi

# git seems to clean up the backup regardless,
# but if its still here lets get rid of it
if [ -e "$backup" ]; then
    rm "$backup"
fi

# apply the diff
sqlite3 "$localDb" "$ancestor2remoteDiff"

