#!/bin/bash

# 定义红色输出的函数
red_echo() {
  echo -e "\033[31m\$1\033[0m"
}

# 自动检测系统架构
ARCH=$(uname -m)

# 根据架构选择正确的 Cloudflare 二进制文件
if [[ "$ARCH" == "x86_64" ]]; then
  CLOUDFLARED_BIN="cloudflared-linux-amd64"
elif [[ "$ARCH" == "aarch64" ]]; then
  CLOUDFLARED_BIN="cloudflared-linux-arm64"
elif [[ "$ARCH" == "armv7l" ]]; then
  CLOUDFLARED_BIN="cloudflared-linux-armhf"
else
  red_echo "不支持的架构: $ARCH"
  exit 1
fi

# 定义CloudFlare二进制文件和版本
CLOUDFLARED_URL="https://cloud.fnmqs.work/cloudflared/"

# 下载并设置权限
red_echo "下载 Cloudflare 二进制文件..."
wget ${CLOUDFLARED_URL}${CLOUDFLARED_BIN} -O cloudflared
if [[ $? -ne 0 ]]; then
  red_echo "下载 Cloudflare 二进制文件失败！"
  exit 1
fi

# 设置文件权限
red_echo "设置文件权限..."
chmod 777 cloudflared
if [[ $? -ne 0 ]]; then
  red_echo "设置文件权限失败！"
  exit 1
fi

# 获取用户输入
read -p "请输入隧道名称: " TUNNEL_NAME
read -p "请输入域名: " DOMAIN
read -p "请输入服务协议 (http/https/tcp/udp): " PROTOCOL
read -p "请输入服务端口: " PORT

# 输入协议验证
while true; do
  read -p "请输入服务协议 (http/https/tcp/udp): " PROTOCOL
  if [[ "$PROTOCOL" =~ ^(http|https|tcp|udp)$ ]]; then
    break
  else
    red_echo "无效的协议！请使用 http、https、tcp 或 udp。"
  fi
done


# 登录 Cloudflare
red_echo "登录 Cloudflare，请按提示操作..."
red_echo "请复制链接并在浏览器中打开以完成登录。"
if ! ./cloudflared login; then
  red_echo "Cloudflare 登录失败！"
  exit 1
fi

# 检查是否生成了 cert.pem 文件
if [[ ! -f ~/.cloudflared/cert.pem ]]; then
  red_echo "登录失败！没有生成 cert.pem 文件。"
  red_echo "请访问本脚本作者的博客，查看并留言获取帮助：[https://www.fnmqs.work/archives/168/]"
  exit 1
fi

# 创建隧道
./cloudflared tunnel create ${TUNNEL_NAME}

# 获取隧道 ID 从 .json 文件名
TUNNEL_JSON_FILE=$(ls ~/.cloudflared/*.json 2>/dev/null)
if [[ -z "$TUNNEL_JSON_FILE" ]]; then
  red_echo "未找到 .json 文件！"
  red_echo "请访问本脚本作者的博客，查看并留言获取帮助：[https://www.fnmqs.work/archives/168/]"
  exit 1
fi

# 提取 ID（即文件名去掉 .json 后缀）
TUNNEL_ID=$(basename "$TUNNEL_JSON_FILE" .json)

# 创建并编辑 systemd 服务文件
red_echo "创建 systemd 服务文件..."
cat <<EOF | sudo tee /etc/systemd/system/cloudflared.service
[Unit]
Description=Cloudflare Tunnel
After=network.target

[Service]
ExecStart=/root/cloudflared --loglevel debug --config /root/.cloudflared/config.yaml tunnel run ${TUNNEL_NAME}
Restart=always
User=root
Group=nogroup

[Install]
WantedBy=multi-user.target
EOF

# 检查 systemd 服务文件是否创建成功
if [[ $? -ne 0 || ! -f /etc/systemd/system/cloudflared.service ]]; then
  red_echo "创建 systemd 服务文件失败！请检查权限或路径。"
  exit 1
fi


# 创建配置文件
red_echo "创建 Cloudflare 配置文件..."
mkdir -p ~/.cloudflared
touch ~/.cloudflared/config.yaml

cat <<EOF | sudo tee ~/.cloudflared/config.yaml
tunnel: ${TUNNEL_ID}
credentials-file: ~/.cloudflared/${TUNNEL_ID}.json

ingress:
  - hostname: ${DOMAIN}
    service: ${PROTOCOL}://localhost:${PORT}
  - service: http_status:404
EOF

# 启动并设置开机自启
red_echo "启动 Cloudflare Tunnel 并设置开机自启..."
sudo systemctl start cloudflared
sudo systemctl enable cloudflared

red_echo "Cloudflare Tunnel 配置完成！"
red_echo "服务启动之后前往 cloudflare，将 ${DOMAIN} 使用 CNAME 解析到 ${TUNNEL_ID}.cfargotunnel.com"

