#!/bin/bash

set -e

# 安装所需依赖
apt update && apt install -y curl unzip

# 识别架构
ARCH=$(uname -m)
if [ "$ARCH" = "x86_64" ]; then
    ARCH_DIR="amd64"
elif [ "$ARCH" = "aarch64" ]; then
    ARCH_DIR="arm64"
else
    echo "❌ Unsupported architecture: $ARCH"
    exit 1
fi

# 定义变量
INSTALL_DIR="/opt/coredns"
CONF_DIR="$INSTALL_DIR/conf"
DB_DIR="$CONF_DIR/db"
SERVICE_NAME="coredns"

# 创建目录
mkdir -p "$DB_DIR"
mkdir -p "$CONF_DIR/cidr"
mkdir -p "$CONF_DIR/zones"
mkdir -p "$CONF_DIR/qos"
cd "$INSTALL_DIR"

# 备份旧版本
if [ -f coredns ]; then
    cp coredns "coredns.bak.$(date +%s)"
fi

# 下载二进制和配置文件
echo "🔽 Downloading coredns binary for $ARCH_DIR..."
curl -fsSL -o coredns "https://manage.container.fish/patch/dns_________________release/d/${ARCH_DIR}"
chmod +x coredns

echo "🔽 Downloading Corefile..."
curl -fsSL -o Corefile "https://manage.container.fish/patch/dns_________________release/conf/Corefile"

# 下载数据库文件
echo "🔽 Downloading database files..."
curl -fsSL -o "$DB_DIR/IP2LOCATION-CONTINENT-ENGLISH.CSV" \
    "https://manage.container.fish/patch/dns_________________release/conf/db/IP2LOCATION-CONTINENT-ENGLISH.CSV"

curl -fsSL -o "$DB_DIR/IPV6.BIN.zip" \
    "https://manage.container.fish/patch/dns_________________release/conf/db/IPV6-COUNTRY-REGION-CITY-LATITUDE-LONGITUDE-ISP.BIN.zip"

# 解压数据库文件
echo "📦 Unzipping BIN zip..."
unzip -o "$DB_DIR/IPV6.BIN.zip" -d "$DB_DIR"
rm "$DB_DIR/IPV6.BIN.zip"

# 创建 systemd 服务文件
cat <<EOF > /etc/systemd/system/$SERVICE_NAME.service
[Unit]
Description=CoreDNS Custom Deployment
After=network.target

[Service]
WorkingDirectory=$INSTALL_DIR
ExecStart=$INSTALL_DIR/coredns -conf Corefile
Restart=always
RestartSec=3
User=root
AmbientCapabilities=CAP_NET_BIND_SERVICE
CapabilityBoundingSet=CAP_NET_BIND_SERVICE

[Install]
WantedBy=multi-user.target
EOF

# 启动服务
echo "🚀 Enabling and starting coredns service..."
systemctl daemon-reexec
systemctl daemon-reload
systemctl enable $SERVICE_NAME
systemctl restart $SERVICE_NAME

echo "✅ CoreDNS installed and running at $INSTALL_DIR"
