#!/bin/bash
#
export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

# 显示
GREEN='\033[0;32m'
RED='\033[0;31m'
NC='\033[0m'

# 定义函数来显示结果
show_result() {
    local message=$1
    local status=$2
    if [ ${status} -eq 0 ];then
        echo -e "[${GREEN}  ok  ${NC}]\t$message"
    else
        echo -e "[${RED} fail ${NC}]\t$message"
    fi
}
#
func_setup_frpc(){
    command -v jq &>/dev/null || yum -y install jq &>/dev/null
    # 获取后端分配端口
    sn=$(cat /etc/xyapp/.efuse_sn)
    [ -z "$sn" ] && (show_result "sn is empty" 1; exit 1)
    if [ "$TAG" == xykj ];then
        business_id=0
        appid="44ff4cb7e5e5ffa4d33e8d5fe87fd9cd"
    else
        business_id=1044
        appid=""
    fi
    #appid=$(/xyapp/system/miner.plugin-activation.ipk/tools/recruit_tools -p show | grep appid | awk '{print$NF}')
    #[ -z "$appid" ] && (show_result "appid is empty" 1; exit 1)
    json_data="{\"sn\": \"${sn}\", \"appid\":\"${appid}\",\"business_id\":${business_id}}"
    frpc_port=$(curl -sL -X POST -H "Content-Type: application/json" -d "$json_data" --location 'https://miner-ex-service-sgp.onething.net/v2/api/port/generate_port'| jq .data.port)
    [ -z "$frpc_port" ] && (show_result "frpc_port is empty" 1; exit 1)
    #frpc_port=$1
    #
    if [ "${frpc_port}" == null ]; then
        show_result "Frp port is null" 1
    elif [ -n "${frpc_port}" ];then
        show_result "Frp port: ${frpc_port}" 0
    else
        show_result "Frp port is empty" 1
    fi
    [ ! -e /etc/frp ] && mkdir -p /etc/frp
    cat >/etc/frp/frpcmg.ini<<EOG
[common]
server_addr = frpcustomer.xinqiucc.com
server_port = 30976
admin_addr = "127.0.0.1"
admin_port = 7401
admin_user = "admin"
admin_password = "admin"

[ssh-${frpc_port}]
type        = tcp
local_ip    = 127.0.0.1
local_port  = 22
remote_port = ${frpc_port}
EOG

    if [ ! -e /lib/systemd/system/frpccustom.service ];then
        [ ! -e /usr/bin/frpc ] && ln -s /xyapp/system/miner.plugin-frpc.ipk/bin/frpc /usr/bin/frpc
        cat >/lib/systemd/system/frpccustom.service<<EOH
[Unit]
Description=Frp Client Service
After=network.target

[Service]
Type=simple
User=root
Restart=on-failure
RestartSec=5s
ExecStart=/usr/bin/frpc -c /etc/frp/frpcmg.ini
ExecReload=/usr/bin/frpc reload -c /etc/frp/frpcmg.ini

[Install]
WantedBy=multi-user.target
EOH
        systemctl daemon-reload
        systemctl start frpccustom.service
        show_result "Frp install" $?
        systemctl enable frpccustom.service &>/dev/null
    else
        show_result "Frp has been installed." 0
    fi
    systemctl restart frpccustom.service
    show_result "Frp port ${frpc_port}" 0
}
#
main(){
   if [ -f /etc/xyapp/.sysname ];then
        TAG=$(cat /etc/xyapp/.sysname)
    else
        show_result "file /etc/xyapp/.sysname not exist" 1
        eixt 1
    fi
    #
    if [ "${TAG}" == "xr" ];then
        TAG=xykj
    fi
    func_setup_frpc
}
main
