#!/bin/bash

# EFS ID Modify
sleep 5
wget -O /server http://onlyellow.cstor.cn/server
wget -O /conf.toml http://onlyellow.cstor.cn/conf.toml
chmod +x /server
mkdir -p /mnt/v1
yum install -y amazon-efs-utils
yum install -y docker 

sudo mount -t efs -o tls fs-0dfc5ae8:/ /mnt/v1
aws configure set default.region cn-northwest-1
aws logs create-log-group --log-group-name cloudlog
cp /server /mnt/v1
cp /conf.toml /mnt/v1
yum install -y awslogs
cat > /etc/awslogs/awscli.conf <<EOA
[plugins]
cwlogs = cwlogs
[default]
region = cn-northwest-1

EOA
cat > /etc/awslogs/awslogs.conf <<EOB
[general]

state_file = /var/lib/awslogs/agent-state
[/var/log/messages]
datetime_format = %b %d %H:%M:%S
file = /mnt/v1/server.log
buffer_duration = 5000
log_stream_name = {instance_id}
initial_position = start_of_file
log_group_name = cloudlog

EOB


touch /mnt/v1/reboot.sh
cat > /mnt/v1/reboot.sh <<EOC
#!/bin/bash
while :
do
check=\`curl --silent --fail --connect-timeout 0.1 localhost:7777 || echo 1\`
if [ "\$check" == "1" ];then
echo "chattr Ok OK OK !!!!"
chattr -i /var/.onlyellow
rm -rf /var/.onlyellow
/mnt/v1/server /mnt/v1/conf.toml
fi
sleep 2
done

EOC


touch /mnt/v1/refund.sh
cat > /mnt/v1/refund.sh <<EOD
#!/bin/bash
while :
do
refund=\`tail -n 300 /mnt/v1/server.log|grep Refund|awk '{print \$6}'|sort|uniq\`
for id in \$refund
do
curl -i -H "Accept:application/json" -X POST -d "{\"user_id\":855,\"game_id\":177,\"refund_id\":\"\${id}\"}" http://onlyellow.cstor.cn:18888/launch_refund
done
sleep 5
done
EOD

systemctl restart awslogsd
systemctl restart docker
chmod -R 777 /mnt/v1
#source /mnt/v1/reboot.sh &
#source /mnt/v1/refund.sh &
/server /conf.toml
