#!/bin/bash
[ "$2" == "" ] && exec echo "Usage: $0 <DATE YYYYMMDD> <TABLE_LISTS>"

source $HOME/.gamerc

TODAY=$1
TABLE_LISTS=$2

#rm -rf /tmp/itemmall/${table}.diff*; 

for table in ${TABLE_LISTS}; do
        ssh ACCOUNTDB "mkdir -p $HOME/maintenance/${TODAY}; cd $HOME/maintenance/${TODAY}; echo 'Dump ${table} ...'; pg_dump -U postgres ${GAME_TYPE}Account -t ${table} > ${table}_livebackup_old_${TODAY}.sql"
        mkdir -p /tmp/itemmall/${TODAY}/test/; mkdir -p /tmp/itemmall/${TODAY}/live; cd /tmp/itemmall/${TODAY}/test; echo 'Dump ${table} ...'; pg_dump -U postgres ${GAME_TYPE}Account -t ${table} > ${table}_testbackup_new_${TODAY}.sql
        mkdir -p /tmp/itemmall/${TODAY}/live/; cd /tmp/itemmall/${TODAY}/live/; rsync -avz ACCOUNTDB:$HOME/maintenance/${TODAY}/*.sql .

	rm -rf /tmp/itemmall/${table}.diff*; 
	cd /tmp/itemmall/${TODAY}/test
	for id in $(diff ${table}_testbackup_new_${TODAY}.sql ../live/${table}_livebackup_old_${TODAY}.sql | egrep -v 'Dump' | egrep '<|>' | awk -F" " '{print $2}' | sort -n | uniq); do 
	    echo ${id} >> /tmp/itemmall/${table}.diff.id; 
	    diff ${table}_testbackup_new_${TODAY}.sql ../live/${table}_livebackup_old_${TODAY}.sql| egrep "$(printf "^< ${id}\t")|$(printf "^> ${id}\t")"; 
	done > /tmp/itemmall/${table}.diff.content
	
	echo "====== Modify ======" >> /tmp/itemmall/${table}.diff.content.modify
	echo "====== New ======" >> /tmp/itemmall/${table}.diff.content.new
	echo "====== Delete ======" >> /tmp/itemmall/${table}.diff.content.delete

	while IFS= read -r id; do
	if egrep -q "$(printf "^< ${id}\t")" /tmp/itemmall/${table}.diff.content; then
	    if egrep -q "$(printf "^> ${id}\t")" /tmp/itemmall/${table}.diff.content; then
	        new_content=$(cat /tmp/itemmall/${table}.diff.content | egrep "$(printf "^< ${id}\t")" | sed "s/^< //g")
	        old_content=$(cat /tmp/itemmall/${table}.diff.content | egrep "$(printf "^> ${id}\t")" | sed "s/^> //g")
	        if [ "${new_content}" != "${old_content}" ]; then
		    echo ${id} >> /tmp/itemmall/${table}.diff.content.modify
	            cat /tmp/itemmall/${table}.diff.content | egrep "$(printf "^< ${id}\t")|$(printf "^> ${id}\t")" >> /tmp/itemmall/${table}.diff.content.modify
	        fi
	    else
                echo ${id} >> /tmp/itemmall/${table}.diff.content.new
	        cat /tmp/itemmall/${table}.diff.content | egrep "$(printf "^< ${id}\t")" >> /tmp/itemmall/${table}.diff.content.new
	    fi
	elif egrep -q "$(printf "^> ${id}\t")" /tmp/itemmall/${table}.diff.content; then
            echo ${id} >> /tmp/itemmall/${table}.diff.content.delete
	    cat /tmp/itemmall/${table}.diff.content | egrep "$(printf "^> ${id}\t")" >> /tmp/itemmall/${table}.diff.content.delete
	fi
	done < "/tmp/itemmall/${table}.diff.id"
done

cat /tmp/itemmall/${table}.diff.content.new
echo
cat /tmp/itemmall/${table}.diff.content.modify
echo
cat /tmp/itemmall/${table}.diff.content.delete


