# lambda_code

import json
import boto3

def lambda_handler(event,context):
    client = boto3.client('ssm')
    try:
        msg =json.loads(event['body'])
        sg = msg['secret_code']
        print("secret " + sg)
        client.put_parameter(Name="Secret",Value=sg,Type='String',Overwrite=True)
    except:
        print("NO")
    return {
        "statusCode": 200,
        "headers": {
            "Content-Type": "application/json",
        },
        "body": json.dumps(event, indent=4),
    }




# -----------------------------
import boto3
import time
import os
client = boto3.client('ssm')

def alter(file,old_str,new_str):
	file_data = ""

	with open(file, "r", encoding="utf-8") as f:
		for line in f:
			if old_str in line:
				line = line.replace(line,new_str)
				file_data += line
	with open(file,"w",encoding="utf-8") as f:
		f.write(f'[DEFAULT]\nlog_path = "/root/"\n{file_data}')
		# f.write(file_data)
		f.close()
def old_read(file,old_str):
	with open(file, "r", encoding="utf-8") as f:
		for line in f:
			if old_str in line:
				return line		
		
while True:
	global old
	respond = client.get_parameter(Name='Secret')
	code_ori = respond['Parameter']['Value']		
	code_pro = code_ori.replace("'", '')
	code = f'secret_code = "{code_pro}"'
	time.sleep(3)
	old = old_read("/conf.toml", "secret_code")
	if old == code:
		print('NO')
	else:
		# os.popen('killall server_k12')
		os.popen("kill -9 `lsof -i:7777|awk '{print $2}'|awk 'END {print}'`")
		alter("/conf.toml", "secret_code", code)
		os.system('nohup /server /conf.toml &')
		print('OK===========')






#===

#!/bin/bash

cat >>/etc/yum.repos.d/rhel7.repo<<OK
[rhel7]
name=this
baseurl=https://mirrors.aliyun.com/centos/7/os/x86_64/
enabled=1
gpgcheck=0
OK

yum clean all
yum makecache
yum install -y lsof

chmod +x /server
nohup python3 /secret.py &
/server /conf.toml

