#!/bin/sh

function _help() {
    echo "Usage: patch_fragment <kernel path> <old> <new>";
    exit 1;
}

kernel_path=$1;
shift
orig=$1
shift
new=$1
shift

if [ -z "$kernel_path" -o -z "$orig" -o -z "$new" ]; then
	_help;
fi

# mangle orig so it's relative to the top of the linux source
kernel_path=`echo "$kernel_path" | sed -e 's/\/+$//'`
kernel_path=`echo "$kernel_path" | sed -e 's/\/[^/]*$//'`
relative=${orig:$((${#kernel_path} + 1))};

if ! [ -a $new ]; then
	echo "$new not found" >&2;
	exit 2;
fi

if ! [ -a $orig ];  then
    new_time=`ls --full-time $new`;
    new_time=`echo $new_time | sed -e 's/^\([^ ][^ ]*[[:blank:]][[:blank:]]*\)\{5\}\(\([^ ][^ ]*[[:blank:]][[:blank:]]*\)\{5\}\).*/\2/'`
    echo "--- $relative.orig $new_time";
    echo "+++ $relative $new_time";
    count=`cat $new | wc -l`;
    echo -e "@@ -0,0 +1,$((count)) @@\n";
    cat $new | sed -e 's/^.*/+&/';
else
    expr1="s|\(^---[[:blank:]][[:blank:]]*\)${orig}\([[:blank:]][[:blank:]]*.*\)|\1${relative}\.orig\2|"
    expr2="s|\(^\+\+\+[[:blank:]][[:blank:]]*\)${new}\([[:blank:]][[:blank:]]*.*\)|\1${relative}\2|"
    ( diff -u $orig $new | \
    sed -e "$expr1" -e "$expr2" ) || \
    ( echo "couldn't diff files" && exit 3 );
fi

exit 0;
