#!/bin/bash

DBNAME="$1"

###
#任務 10071
#狀態 1 : Sucessful  (任務完成結束)

#更新 DB
#UPDATE player_characters SET state_flags = state_flags | 4;
###

mission_id="10071"

#-- final_mission_state1
echo ""
echo "======== FM1 MIDs: 10071, STATE: 1 ========" 
echo ""
#echo "[PRE CHECK]"
echo "WITH t1 AS (SELECT player_id FROM final_mission_state1 WHERE index=(${mission_id}-1)/10 AND state=(1<<(${mission_id}-1)%10*3) | (state&(~(7 << (${mission_id}-1)%10*3)))) SELECT COUNT(player_id) FROM t1"
psql -U postgres ${DBNAME} -c "WITH t1 AS (SELECT player_id FROM final_mission_state1 WHERE index=(${mission_id}-1)/10 AND state=(1<<(${mission_id}-1)%10*3) | (state&(~(7 << (${mission_id}-1)%10*3)))) SELECT COUNT(player_id) FROM t1"

echo ""
#echo "[UPDATING] ..."
echo "WITH t1 AS (SELECT player_id FROM final_mission_state1 WHERE index=(${mission_id}-1)/10 AND state=(1<<(${mission_id}-1)%10*3) | (state&(~(7 << (${mission_id}-1)%10*3))) ORDER BY player_id) UPDATE player_characters SET state_flags = state_flags | 4 WHERE id IN (SELECT player_id FROM t1)"
psql -U postgres ${DBNAME} -c  "WITH t1 AS (SELECT player_id FROM final_mission_state1 WHERE index=(${mission_id}-1)/10 AND state=(1<<(${mission_id}-1)%10*3) | (state&(~(7 << (${mission_id}-1)%10*3))) ORDER BY player_id) UPDATE player_characters SET state_flags = state_flags | 4 WHERE id IN (SELECT player_id FROM t1)"

#-- final_mission_state2
echo ""
echo "======== FM2 MIDs: 10071, STATE: 1 ========" 
echo ""
#echo "[PRE CHECK]"
echo "WITH t1 AS (SELECT player_id FROM final_mission_state2 WHERE index=(${mission_id}-1)/10 AND state=(1<<(${mission_id}-1)%10*3) | (state&(~(7 << (${mission_id}-1)%10*3)))) SELECT COUNT(player_id) FROM t1"
psql -U postgres ${DBNAME} -c "WITH t1 AS (SELECT player_id FROM final_mission_state2 WHERE index=(${mission_id}-1)/10 AND state=(1<<(${mission_id}-1)%10*3) | (state&(~(7 << (${mission_id}-1)%10*3)))) SELECT COUNT(player_id) FROM t1"
echo ""
#echo "[UPDATING] ..."
echo "WITH t1 AS (SELECT player_id FROM final_mission_state2 WHERE index=(${mission_id}-1)/10 AND state=(1<<(${mission_id}-1)%10*3) | (state&(~(7 << (${mission_id}-1)%10*3))) ORDER BY player_id) UPDATE player_characters SET state_flags = state_flags | 4 WHERE id IN (SELECT player_id FROM t1)"
psql -U postgres ${DBNAME} -c  "WITH t1 AS (SELECT player_id FROM final_mission_state2 WHERE index=(${mission_id}-1)/10 AND state=(1<<(${mission_id}-1)%10*3) | (state&(~(7 << (${mission_id}-1)%10*3))) ORDER BY player_id) UPDATE player_characters SET state_flags = state_flags | 4 WHERE id IN (SELECT player_id FROM t1)"

