#!/bin/bash

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

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/lambda_function.py
cat > /mnt/v1/lambda_function.py <<EOC

import json
import pymysql
import boto3

def updata_db(key1,value1):
    conn2 = pymysql.connect(
        host='DNSName',
        port=3306,
        user='admin',
        passwd='xcloud1234',
        db='cmd',
        charset='utf8mb4')

    cs2 = conn2.cursor()
    select_sql = f'INSERT INTO kv(mykey,myvalue) VALUES ("{key1}", "{value1}");'
    cs2.execute(select_sql)
    conn2.commit()
    cs2.close()
    conn2.close()

def lambda_handler(event, context):
    # TODO implement
    print(event)

EOC

mkdir -p /mnt/v1/package
pip3 install --target /mnt/v1/package pymysql
cd /mnt/v1/package
zip -r9 ../function.zip .
cd ..
zip -g function.zip lambda_function.py
cd /mnt/v1
aws lambda update-function-code --function-name hehe-la --zip-file fileb://function.zip

touch /mnt/v1/Dockerfile
cat > /mnt/v1/Dockerfile <<EOB
FROM amazonlinux
WORKDIR /
COPY conf.toml /conf.toml
COPY server /server
COPY ent.sh /ent.sh
RUN chmod 777 /ent.sh
ENTRYPOINT ["/ent.sh"]

EOB

touch /mnt/v1/ent.sh
cat > /mnt/v1/ent.sh <<EOB
#!/bin/bash
chmod -R 777 /mnt/v1
chmod +x /server
/mnt/v1/server /mnt/v1/conf.toml

EOB

systemctl restart awslogsd
systemctl restart docker
cd /mnt/v1

chmod -R 777 /mnt/v1
/server /conf.toml
