#!/bin/bash
[ "$6" == "" ] && exec echo "Usage: $0 <DB_NAME> <XLUSER_ID> <CHAR_ID> <MISSION_ID> <MISSION_STATE_BEFORE> <MISSION_STATE_AFTER>"

DB_NAME="$1"
XLUSER_ID="$2"
CHAR_ID="$3"
MISSION_ID="$4"
MISSION_STATE_BEFORE="$5"
MISSION_STATE_AFTER="$6"

POSTFIX=$(psql -U postgres ${DB_NAME} -c "COPY (SELECT postfix FROM player_characters WHERE account_name = '${XLUSER_ID}' AND id = ${CHAR_ID}) TO STDOUT CSV;")
#psql -U postgres ${DB_NAME} -c "COPY (SELECT postfix FROM player_characters WHERE account_name = '${XLUSER_ID}' AND id = ${CHAR_ID}) TO STDOUT CSV;"

PID1=$(psql -U postgres ${DB_NAME} -c "COPY (SELECT DISTINCT player_id FROM final_mission_state${POSTFIX} WHERE ( player_id IN ( SELECT id FROM player_characters WHERE postfix = '${POSTFIX}' AND account_name = '${XLUSER_ID}' AND id = ${CHAR_ID} ) ) AND ( ( player_id IN ( SELECT player_id FROM final_mission_state${POSTFIX} WHERE index =(${MISSION_ID}- 1) / 10 AND ( state = ( ${MISSION_STATE_BEFORE} <<(${MISSION_ID} - 1) % 10 * 3 ) | ( state & ( ~( 7 << (${MISSION_ID} - 1) % 10 * 3 ) ) ) ) ) ) )  ORDER BY player_id) TO STDOUT CSV;")
#psql -U postgres ${DB_NAME} -c "COPY (SELECT DISTINCT player_id FROM final_mission_state${POSTFIX} WHERE ( player_id IN ( SELECT id FROM player_characters WHERE postfix = '${POSTFIX}' AND account_name = '${XLUSER_ID}' AND id = ${CHAR_ID} ) ) AND ( ( player_id IN ( SELECT player_id FROM final_mission_state${POSTFIX} WHERE index =(${MISSION_ID}- 1) / 10 AND ( state = ( ${MISSION_STATE_BEFORE} <<(${MISSION_ID} - 1) % 10 * 3 ) | ( state & ( ~( 7 << (${MISSION_ID} - 1) % 10 * 3 ) ) ) ) ) ) )  ORDER BY player_id) TO STDOUT CSV;"

if [ ! -z "${PID1}" ]; then
	for player_id in ${PID1}; do
		#echo "UPDATE final_mission_state${POSTFIX} SET state = (${MISSION_STATE_AFTER}<<(${MISSION_ID}-1)%10*3) | ( state & (~(7 << (${MISSION_ID}-1)%10*3)) ) WHERE index=(${MISSION_ID}-1)/10 AND player_id = ${CHAR_ID};"
		psql -U postgres ${DB_NAME} -c "UPDATE final_mission_state${POSTFIX} SET state = (${MISSION_STATE_AFTER}<<(${MISSION_ID}-1)%10*3) | ( state & (~(7 << (${MISSION_ID}-1)%10*3)) ) WHERE index=(${MISSION_ID}-1)/10 AND player_id = ${CHAR_ID};"
	done
fi
