#!/bin/bash

separator=':'

HLP(){
    echo "$(basename $0) - util to merge identical text files 
from the system layers, may be required for: 
	/etc/shadow
	/etc/group
	/etc/passwd 
when the layers contains new users or groups

Usage: 
	barium $(basename $0) /path/file1 /path/file2 
Keys:
	-i | --inplace  - replace the file with the generated (like sed -i)
	-s | --separator - delimiter for searching the first field (default ':') 
	-h | --help - this help
Examples:
	barium $(basename $0) /etc/shadow
			- show all merged /etc/shadow from system layers on stdout
	barium $(basename $0) -i /etc/groups
			- replace the /etc/groups in top layer by merged
	barium $(basename $0) -i -d '=' /etc/sysconfig/myprog
			- replace the /etc/sysconfig/myprog in top layer by merged,
use '=' as a separator. If this files contains KEY=VAL lines.
"
    exit ${LINENO}
}

#Разбор параметров cmdline
[ $1 ] || HLP
sep=''
while [ "$1" ] ; do
	case $1 in 
	"--help" | "-h" ) HLP ;;
	"-i" | "--inplace" ) INPLACE=yes ;;
	"-s" | "--separ" ) 	shift 
			separator=$1 ;;
	*)  if [ -f $1 ] ; then
		files_list="${files_list}${sep}$1"
		sep=','
	    else
		echo "File $1 is not exists"
		exit ${LINENO}
	    fi;;
	esac
shift
done

echo $files_list |sed 's/,/\n/g' |while read file ; do
    : > /tmp/comparator_tmp.list
    barium ls --raw '${bundle}'$file |xargs cat 2>/dev/null | while read str ; do
	field1=$(echo $str |cut -f1 -d "$separator")
	grep -E -q '^'${field1}${separator}'.+$'  /tmp/comparator_tmp.list || \
	echo $str >> /tmp/comparator_tmp.list
    done
    if [ "$INPLACE" ] ; then 
	mv $file "${file}~"
	mv /tmp/comparator_tmp.list $file
    else
	cat /tmp/comparator_tmp.list
	rm -f /tmp/comparator_tmp.list
    fi
done
