#!/usr/bin/env bash
#
# build.sh — Build & Run Helper for DNS-over-TLS Cache Proxy
# Author: niuyuling
# Email: aixiao@aixiao.me
# License: MIT
# -----------------------------------------------------------
# 用途：快速构建、运行和管理 dot 容器镜像。
# 用法：
#   ./build.sh build        构建镜像
#   ./build.sh run          启动容器（后台）
#   ./build.sh logs         查看日志
#   ./build.sh stop         停止容器
#   ./build.sh clean        删除容器和镜像
#   ./build.sh rebuild      重新构建镜像并启动
# -----------------------------------------------------------

set -e

IMAGE_NAME="dot"
CONTAINER_NAME="dot"
TAG="latest"
PORT="853"
CERT_FILE="jinllpay.com.cer"
KEY_FILE="jinllpay.com.key"

# ---------- 函数区 ----------

build() {
    echo "🔨 Building Docker image: ${IMAGE_NAME}:${TAG} ..."
    docker build --build-arg BUILD_DATE=$(date -u +"%Y-%m-%dT%H:%M:%SZ") \
        -t "${IMAGE_NAME}:${TAG}" .
        
    echo "✅ Build complete."
}

run() {
    echo "🚀 Starting container ${CONTAINER_NAME}..."

    # 确保旧容器不冲突
    if docker ps -a --format '{{.Names}}' | grep -w "${CONTAINER_NAME}" >/dev/null 2>&1; then
      echo "⚠️  Existing container found. Removing..."
      docker rm -f "${CONTAINER_NAME}" >/dev/null 2>&1 || true
    fi

    docker run -d \
      --name "${CONTAINER_NAME}" \
      --memory=256m \
      --memory-swap=384m \
      --memory-reservation=128m \
      -p ${PORT}:853 \
      -e CERT_FILE="/app/${CERT_FILE}" \
      -e KEY_FILE="/app/${KEY_FILE}" \
      -v "$(pwd)/${CERT_FILE}:/app/${CERT_FILE}:ro" \
      -v "$(pwd)/${KEY_FILE}:/app/${KEY_FILE}:ro" \
      "${IMAGE_NAME}:${TAG}"

    echo "✅ Container started on port ${PORT}."
}

logs() {
    echo "📜 Showing logs..."
    docker logs -f "${CONTAINER_NAME}"
}

stop() {
    echo "🛑 Stopping container..."
    docker stop "${CONTAINER_NAME}" >/dev/null 2>&1 || true
    docker rm "${CONTAINER_NAME}" >/dev/null 2>&1 || true
    echo "✅ Container stopped and removed."
}

clean() {
    stop
    echo "🧹 Removing image ${IMAGE_NAME}:${TAG}..."
    docker rmi "${IMAGE_NAME}:${TAG}" >/dev/null 2>&1 || true
    echo "✅ Cleanup complete."
}

rebuild() {
    clean
    build
    run
}

bin() {
    DATE=$(date "+%Y-%m-%dT%H:%M:%S")
    a="'"
    eval "CGO_ENABLED=1 GOOS=linux GOARCH=amd64 go build -a -ldflags ${a}-X main.BuildDate=${DATE} -extldflags \"-static -lc\"${a}"

    if test -f dot; then
      upx -9 dot
    fi
}

# ---------- 主逻辑 ----------
case "$1" in
    bin) bin ;;
    build) build ;;
    run) run ;;
    logs) logs ;;
    stop) stop ;;
    clean) clean ;;
    rebuild) rebuild ;;
    *)
        echo "Usage: ./build.sh [build|run|logs|stop|clean|rebuild]"
        exit 1
      ;;
esac
