#!/bin/bash
#
# Slackified side-by-side merge of file differences. Heavily based on
# the slackpkg new-config file merging procedures.
#
# Copyright (C) 2018 Jason Graham <jgraham@compukix.net>
#
# Copying and distribution of this file, with or without modification,
# are permitted in any medium without royalty provided the copyright
# notice and this notice are preserved.  This file is offered as-is,
# without any warranty.
# 
#
# Usage: smerge old-file new-file
#
# Date:
#   2018-05-29
#

MORECMD=${PAGER:-less -r}
EDITCMD=${EDITOR:-nano}

showmenu() {
    echo -e "$1 - \c"
    tput sc
    shift
    while [ $# -gt 0 ]; do
	echo -e "$1"
	tput rc
	shift
    done
}

do_merge() {
    local a=$1
    local b=$2
    
    # in media res. we do the merging right away, but we later allow the user to redo it, if not satisfied with the results.
    rm -f "${a}.smerge"
    echo "Enter '?' in the prompt (%) to display help."
    cp -p "${b}" "${a}.smerge" # <- this is so that the installed merged file will have the same permissions as the .new file
    sdiff -s -o "${a}.smerge" "${a}" "${b}"
    
    GOEXM=0
    while [ $GOEXM -eq 0 ]; do
	showmenu ${a} "(E)dit the merged file" "(K)eep the merged file" "View a diff between the merged and the (N)ew file" "View a diff between the (O)ld and the merged file" "(R)edo the merge" "(V)iew the merged file" "(A)bort the merge"
	read ANSWER
	case "$ANSWER" in
	    E|e)
		if [ -f "${a}.smerge" ]; then
		    $EDITCMD "${a}.smerge"
		else
		    echo -e "Nothing was merged yet..."
		fi
		;;
	    K|k)
		if [ -f "${a}.smerge" ]; then
		    if [ -e "${a}" ]; then
			mv "${a}" "${a}.orig"
		    fi
		    mv "${a}.smerge" "${a}"
		    GOEXM=1
		    GOEX=1
		else
		    echo -e "Nothing was merged yet..."
		fi
		;;
	    N|n)
		if [ -f "${a}.smerge" ]; then
		    diff -u "${a}.smerge" "${b}" | $MORECMD
		else
		    echo -e "Nothing was merged yet..."
		fi
		;;
	    O|o)
		if [ -f "${a}.smerge" ]; then
		    diff -u "${a}" "${a}.smerge" | $MORECMD
		else
		    echo -e "Nothing was merged yet..."
		fi
		;;
	    R|r)
		rm -f "${a}.smerge"
		echo "Enter '?' in the prompt (%) to display help."
		cp -p "${b}" "${a}.smerge" # <- this is so that the installed merged file will have the same permissions as the .new file
		sdiff -s -o "${a}.smerge" "${a}" "${b}"
		;;
	    V|v)
		if [ -f "${a}.smerge" ]; then
		    $MORECMD "${a}.smerge"
		else
		    echo -e "Nothing was merged yet..."
		fi
		;;
	    A|a)
		rm -f "${a}.smerge"
		GOEXM=1
		;;
	esac
    done

    return 0;
}


if (( $# != 2 )); then
    echo "Usage: `basename $0` old-file new-file"
    exit 1  
fi

if [ ! -e $1 ]; then
    echo "file $1 doesn't exist"
    exit 1;
fi
if [ ! -e $2 ]; then
    echo "file $2 doesn't exist"
    exit 1;
fi

if [[ -z $(diff $1 $2) ]]; then
    exit 0;
fi

do_merge $1 $2
