#!/bin/bash

fulldate=$1
date=$(echo ${fulldate} | cut -c5-)
outputdate=$(date +%Y%m%d)

if [ ! -d ~/www/download/m12global_familywar_seasonreward_${outputdate} ]; then
	mkdir -p ~/www/download/m12global_familywar_seasonreward_${outputdate}
fi

# 合併 SeasonReward Log
cd ~/www/download/m12global_familywar_seasonreward_${outputdate}
if [ ! -d temp ]; then
	mkdir temp
else
	rm -rf temp/*
fi

for file in $(ls m12global_s*_familywar_seasonreward.log); do
	cat ${file} | awk -F"SeasonReward" '{print $2}' | sed 's/\] //' | awk '{if(FNR%2==1) {printf "%s",$0;getline;};print;}' | sed 's/FamilyID \[//;s/\] RewardID\[/,/;s/\], RewardPlayer \[/,/;s/, \],//;s/ //g' > temp/${file}.1st
done

# 將發獎 Log 拆成每個角色ID 一行顯示
cd temp
for file in $(ls m12global_s*_familywar_seasonreward.log.1st); do
	file_prefix=$(echo ${file} | sed 's/.1st//')
	while read line; do
		number=0
		col1=""
		col2=""
		string=""
		IFS=',' read -ra ADDR <<< "${line}"
		for parameter in "${ADDR[@]}"; do
			let number=${number}+1
			if [ ${number} -eq 1 ]; then
				col1=${parameter}
			elif [ ${number} -eq 2 ]; then
				col2=${parameter}
			else
				echo "${col1},${col2},${parameter}" >> ${file_prefix}.2nd
			fi
		done
	done < ${file}
done

# 整理領獎 Log, 只需要 RewardID 跟角色ID
cd ~/www/download/m12global_familywar_seasonreward_${outputdate}
for file in $(ls m12global_s*_familywar_getreward.log); do
	cat ${file} | awk -F"RewardID" '{print $2}' | sed 's/\[//;s/\], /:/' | awk -F":" '{print $1","$3}' > temp/${file}.3rd
done

cd temp
# 比較領獎跟發獎 Log, 將未領獎的輸出至檔案
for file in $(ls m12global_s*_familywar_seasonreward.log.2nd); do
	set=$(echo ${file} | sed 's/m12global_s//;s/_familywar_seasonreward.log.2nd//')
	while read line; do
		temp_str=$(echo ${line} | awk -F"," '{print $2","$3}')
		comparison=$(cat m12global_s${set}_familywar_getreward.log.3rd | grep ${temp_str})
		if [ -z "${comparison}" ]; then
			echo ${line} >> s${set}_familywar_notget.final
		else
			echo ${line} >> s${set}_familywar_get.final
		fi
	done < ${file}
done
