#!/bin/bash
source $HOME/bin/xigncode_settings

for xigncode_info_test in $(PGPASSWORD=$dbpass psql -U ${dbuser} ${dbname} -h CTRL -c "COPY (SELECT id, name, type FROM ${XIGNCODE_LOG_TABLE_NAME} WHERE status = 0 ORDER BY type, created_time DESC) TO STDOUT CSV;"); do
	XIGNCODE_ID=$(echo ${xigncode_info_test} | awk -F',' '{print $1}')
	XIGNCODE_FILENAME=$(echo ${xigncode_info_test} | awk -F',' '{print $2}')
	XIGNCODE_FILETYPE=$(echo ${xigncode_info_test} | awk -F',' '{print $3}')

	if [ -f "$HOME/www/promotion_upload/xigncode_uploads/${XIGNCODE_FILENAME}" ]; then
		LIVE_SYNC=$(PGPASSWORD=$dbpass psql -U ${dbuser} ${dbname} -h CTRL -c "COPY (SELECT live_sync FROM ${XIGNCODE_LOG_TABLE_NAME} WHERE id = ${XIGNCODE_ID}) TO STDOUT;")

		if [ "${LIVE_SYNC}" -eq -1 ]; then
			sudo rm -rf $HOME/www/promotion_upload/xigncode_uploads/${XIGNCODE_FILENAME}
		else
			PGPASSWORD=$dbpass psql -U ${dbuser} ${dbname} -h CTRL -c "UPDATE ${XIGNCODE_LOG_TABLE_NAME} SET live_sync = -1 WHERE type = '${XIGNCODE_FILETYPE}' AND status <> 2 AND id <> ${XIGNCODE_ID};"

			if [ ! -d "$HOME/patch/XIGNCODE" ]; then
				mkdir -p $HOME/patch/XIGNCODE
			fi
			sudo mv $HOME/www/promotion_upload/xigncode_uploads/${XIGNCODE_FILENAME} $HOME/patch/XIGNCODE/.

			own_user=$(whoami)
			sudo chown ${own_user}:${own_user} $HOME/patch/XIGNCODE/${XIGNCODE_FILENAME}

			$HOME/bin/xigncode_patchroot_test_auto ${XIGNCODE_FILENAME} ${XIGNCODE_ID}
		fi
	fi
	echo
done
