#!/bin/bash
version="0.57.0"
#####################说明#########################
#     bash main.sh  安装frpc                     #
#     bash main.sh -p 666 1080  配置frpc端口     #
#     bash main.sh -o start  启动frpc服务        #
#     bash main.sh -o enable 设置frpc开机自启    #
#     bash main.sh -o disable  禁止frpc         #
#################################################

download_url="https://github.9421.eu.org/https://github.com/fatedier/frp/releases/download/"
frpc_config_file="frpc.toml"
key=$(cat /dev/urandom | tr -dc 'a-zA-Z0-9' | head -c 10)
# 默认参数，用于判断是否需要安装
install_flag=true
# 默认操作，用于判断需要执行的操作
operation=""
# 默认端口参数
port1=""
port2=""

# 解析参数
while getopts ":p:o:" opt; do
  case ${opt} in
    p )
      port1=$OPTARG
      shift $((OPTIND-1))
      port2=$1
      shift $((OPTIND-1))
      ;;
    o )
      operation=$OPTARG
      ;;
    \? )
      echo "Invalid option: $OPTARG" 1>&2
      exit 1
      ;;
    : )
      echo "Invalid option: $OPTARG requires an argument" 1>&2
      exit 1
      ;;
  esac
done

# 如果没有操作参数，则默认安装
if [ -z "$operation" ]; then
    operation="install"
fi

# 执行操作
case "$operation" in
    "install")
        # 检查是否已经安装
        if [ -f "/frpc/frpc" ]; then
            echo "frpc已经安装，无需再次安装"
            install_flag=false
        fi
        # 如果需要安装，则执行安装操作
        if [ "$install_flag" = true ]; then
            echo "开始安装frpc"
            wget -N --no-check-certificate ${download_url}v${version}/frp_${version}_linux_arm.tar.gz
            mkdir /frpc
            tar -xzvf frp_${version}_linux_arm.tar.gz
            mv /root/frp_${version}_linux_arm/frpc /frpc
            mv /root/frp_${version}_linux_arm/${frpc_config_file} /frpc
            #写入服务单元配置文件
            cat > /etc/systemd/system/frpc.service<<-EOF
[Unit]
Description = frpc server
After = network.target syslog.target
Wants = network.target

[Service]
Type = simple
ExecStartPre=/bin/sleep 5
Restart=always
ExecStart = /frpc/frpc -c /frpc/frpc.toml

[Install]
WantedBy = multi-user.target
EOF
        fi

        if [ -n "$port1" ] && [ -n "$port2" ]; then
            touch /frpc/${frpc_config_file}
            #写入frpc配置文件
cat > /frpc/${frpc_config_file}<<-EOF
[common]
protocol = tcp
tcp_mux = true
pool_count = 1
tls_enable = false
disable_custom_tls_first_byte = false
token = 1s5tzZNPIe
server_addr = 47.104.228.20
server_port = 7000
[${key}]
type = tcp
local_ip = 127.0.0.1
local_port = ${port1}
remote_port = ${port2}
EOF
        fi
        ;;
    "start")
        echo "启动frpc服务"
        sudo systemctl start frpc
        ;;
    "enable")
        echo "设置frpc开机自启"
        sudo systemctl enable frpc
        ;;
    "disable")
        echo "禁止frpc开机自启"
        sudo systemctl disable frpc
        ;;
    *)
        echo "无效操作: $operation" 1>&2
        exit 1
        ;;
esac

exit 0
