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

DB_NAME="$1"
XLUSER_ID="$2"
CHAR_ID="$3"
MISSION_ID="$4"

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;"

psql -U postgres ${DB_NAME} -c "COPY (SELECT (state&(7*8 ^((${MISSION_ID}-1) % 10) )::INT)/(8 ^((${MISSION_ID}-1) % 10))::INT AS state 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 ( index =(${MISSION_ID}- 1) / 10 ) ) TO STDOUT CSV;"
