#!/bin/sh

# 1. 更新软件源并安装依赖
opkg update && 
opkg install libustream-openssl &&

# 2. 安装配置 nginx
opkg install nginx-mod-luci &&
mkdir -p /etc/nginx/conf.d &&
wget https://file.tyxhetc.cn/config/proxy.conf -P /etc/nginx/conf.d &&
nginx -s reload &&

# 3. 下载指定 frpc 包
wget https://file.tyxhetc.cn/frpc_0.37.1-1_mipsel_24kc.ipk -P /tmp &&
opkg install /tmp/frpc_0.37.1-1_mipsel_24kc.ipk &&

# 4. /etc/frp/frpc.d 下创建对应文件，并添加对应内容：
mkdir -p /etc/frp/frpc.d &&

echo """[common]
server_addr = 8.142.122.40
server_port = 7003

log_file = /var/log/frpc_router.log
log_level = debug
log_max_days = 3

[router_config_$1]
type = tcp
local_ip = 127.0.0.1
local_port = 80
remote_port = $1

[router_ssh_$2]
type = tcp
local_ip = 127.0.0.1
local_port = 22
remote_port = $2

[RSU_config_$3]
type = tcp
local_ip = 192.168.1.99
local_port = 80
remote_port = $3
""" > /etc/frp/frpc.d/frpc_router.ini

echo """[common]
server_addr = 8.142.122.40
server_port = 7004

log_file = /var/log/frpc_RSU.log
log_level = debug
log_max_days = 3

[RSU_business_$4]
type = tcp
local_ip = 192.168.1.99
local_port = 8899
remote_port = $4
""" > /etc/frp/frpc.d/frpc_RSU.ini


# 5. /etc/init.d 下创建对应文件，并添加对应内容：
echo """#!/bin/sh /etc/rc.common

USE_PROCD=1
START=99

start_service() {
    procd_open_instance frpc_router
    procd_set_param command /usr/bin/frpc -c /etc/frp/frpc.d/frpc_router.ini
    procd_set_param respawn \${respawn_threshold:-180} \${respawn_timeout:-5} \${respawn_retry:-5}
    procd_close_instance
}
""" > /etc/init.d/frpc-router

echo """#!/bin/sh /etc/rc.common

USE_PROCD=1
START=99

start_service() {
    procd_open_instance frpc_RSU
    procd_set_param command /usr/bin/frpc -c /etc/frp/frpc.d/frpc_RSU.ini
    procd_set_param respawn \${respawn_threshold:-180} \${respawn_timeout:-5} \${respawn_retry:-5}
    procd_close_instance
}
""" > /etc/init.d/frpc-RSU


# 6. 添加执行权限并开机自启
chmod +x /etc/init.d/frpc-router
chmod +x /etc/init.d/frpc-RSU

/etc/init.d/frpc-router enable
/etc/init.d/frpc-RSU enable


# 7. 启动服务
/etc/init.d/frpc-router start
/etc/init.d/frpc-RSU start


# 8. 删除不需要的安装包
rm -rf /tmp/frpc_0.37.1-1_mipsel_24kc.ipk

