#!/bin/bash

DBNAME="$1"
REQUEST_NAME="mission"
REQUEST_PART="1"
SET_ID=$(echo ${DBNAME} | sed 's/DJDB//;s/_LIVE//;s/_20241023//')
TABLE_NAME="xl_20241023_del_lover_s${SET_ID}"
FILENAME="/tmp/s${SET_ID}_modify_${REQUEST_NAME}_${REQUEST_PART}.sql"

rm -rf ${FILENAME}

###
# 執行任務編號 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2179 2180 2181 3399 3400 3401 4753 4754 4755 3564 3565 3566 3567 任務狀態設定 未承接 ( 2 )
###
mission_id_exec="2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2179 2180 2181 3399 3400 3401 4753 4754 4755 3564 3565 3566 3567"
mission_id_exec_state=2

#-- final_mission_state1

PID1=$(psql -U postgres ${DBNAME} -c "COPY (SELECT char_id FROM ${TABLE_NAME} WHERE postfix = '1' ORDER BY char_id) TO STDOUT CSV;")

if [ ! -z "${PID1}" ]; then
for player_id in ${PID1}; do
        for mission_id in ${mission_id_exec}; do
                #沒有的新增 ( index )
                echo "INSERT INTO final_mission_state1 (player_id, index, state) SELECT ${player_id}, (${mission_id}-1)/10, 0 WHERE NOT EXISTS (SELECT player_id, index FROM final_mission_state1 WHERE (player_id, index) = (${player_id}, (${mission_id}-1)/10));" >> ${FILENAME}

                #更新對應任務ID 狀態 ( state )
                echo "UPDATE final_mission_state1 SET state = (${mission_id_exec_state}<<(${mission_id}-1)%10*3) | ( state & (~(7 << (${mission_id}-1)%10*3)) ) WHERE index=(${mission_id}-1)/10 AND player_id = ${player_id};" >> ${FILENAME}
        done
done
fi

#-- final_mission_state2

PID2=$(psql -U postgres ${DBNAME} -c "COPY (SELECT char_id FROM ${TABLE_NAME} WHERE postfix = '2' ORDER BY char_id) TO STDOUT CSV;")

if [ ! -z "${PID2}" ]; then
for player_id in ${PID2}; do
        for mission_id in ${mission_id_exec}; do
                #沒有的新增 ( index )
                echo "INSERT INTO final_mission_state2 (player_id, index, state) SELECT ${player_id}, (${mission_id}-1)/10, 0 WHERE NOT EXISTS (SELECT player_id, index FROM final_mission_state2 WHERE (player_id, index) = (${player_id}, (${mission_id}-1)/10));" >> ${FILENAME}

                #更新對應任務ID 狀態 ( state )
                echo "UPDATE final_mission_state2 SET state = (${mission_id_exec_state}<<(${mission_id}-1)%10*3) | ( state & (~(7 << (${mission_id}-1)%10*3)) ) WHERE index=(${mission_id}-1)/10 AND player_id = ${player_id};" >> ${FILENAME}
        done
done
fi

psql -U postgres ${DBNAME} -c "\i ${FILENAME}"
