#!/bin/bash
# 0 is diff and move else is diff or exit, without ${1} is clean

if [ -z "${1}" ]; then
	rm -f a.o a.out a.swf a.swf.x a.swf.log a.swf.xx
	if [ -e .expected/a.swf ]; then rm .expected/a.swf; fi
	if [ -e .expected/a.swf.x ]; then rm .expected/a.swf.x; fi
	if [ -e .expected/a.swf.xx ]; then rm .expected/a.swf.xx; fi
	if [ -e .expected/a.swf.x32 ]; then rm .expected/a.swf.x32; fi
	if [ -e .expected/a.swf.xx32 ]; then rm .expected/a.swf.xx32; fi
else
	. ./integ && {
		. ./xxd
		smart_diff () {
			diff ${1} ${2}
			if [ $? = 0 ]; then
				ok="${ok} + `du -b ${1}`"
				return 0
			fi
			if [ -n "${3}" ]; then return 1; fi
			a=`stat --printf="%s" ${1}`
			b=`stat --printf="%s" ${2}`
			base64 ${1}
			echo
			base64 ${2}
			if [ ${a} = ${b} ]; then
				echo size equal ${a}
				if [ -n "`which xxd`" ]; then
					xxd${xxd_args}${1} > 1
					xxd${xxd_args}${2} > 2
					diff 1 2
					rm 1 2
				fi
			fi
			return 1
		}
		smart_ask () {
			stat --printf="\n%s\n" .expected/a.swf${1}
			stat --printf="%s\n" a.swf${2}
			echo y \? m \?; read -n1 -t $((60*60*24)) ans
			if [ "${ans}" = "m" ]; then
				if [ -z "${1}" ]; then
					swfdump -Dd .expected/a.swf${1} > 1
					swfdump -Dd a.swf${2} > 2
				else
					xxd${xxd_args}.expected/a.swf${1} > 1
					xxd${xxd_args}a.swf${2} > 2
				fi
				diff 1 2
				echo y \?; read -n1 -t $((60*60*24)) ans
				rm 1 2
			fi
			if [ "${ans}" != "y" ]; then { echo not ok; exit 1; } fi
			base64 a.swf${2} > .expected/a.swf${1}.txt #this is ok with ln
		}

		base64 -d .expected/a.swf.txt > .expected/a.swf || { echo not ok; exit 1; }
		smart_diff .expected/a.swf a.swf
		if [ $? != 0 ]; then
			if [ ${1} != 0 ]; then { echo not ok; exit 1; } fi
			smart_ask
		fi

		if [ "${conv_64}" = 1 ]; then
			v=32
		fi
		base64 -d .expected/a.swf.x${v}.txt > .expected/a.swf.x${v} || { echo not ok; exit 1; }
		smart_diff .expected/a.swf.x${v} a.swf.x
		if [ $? != 0 ]; then
			if [ ${1} != 0 ]; then { echo not ok; exit 1; } fi
			smart_ask .x${v} .x
		fi
		base64 -d .expected/a.swf.xx${v}.txt > .expected/a.swf.xx${v} || { echo not ok; exit 1; }
		smart_diff .expected/a.swf.xx${v} a.swf.xx
		if [ $? != 0 ]; then
			if [ ${1} != 0 ]; then { echo not ok; exit 1; } fi
			smart_ask .xx${v} .xx
		fi

		smart_diff .expected/a.swf.log a.swf.log x
		if [ $? != 0 ]; then
			if [ ${1} != 0 ]; then { echo not ok; exit 1; } fi
			echo y \?; read -n1 -t $((60*60*24)) ans
			if [ "${ans}" != "y" ]; then { echo not ok; exit 1; } fi
			mv a.swf.log .expected
		fi
	}
	echo ${ok}
fi
