#!/bin/bash
# =============================================================================
# Docker Registry 安裝腳本
# =============================================================================

set -e

# 顏色
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

log() { echo -e "${GREEN}[INFO]${NC} $1"; }
warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }
error() { echo -e "${RED}[ERROR]${NC} $1"; exit 1; }

# 配置
REGISTRY_USER="${REGISTRY_USER:-admin}"
REGISTRY_PASSWORD="${REGISTRY_PASSWORD:-Wooo_Registry_2026}"
DOMAIN="registry.wooo.work"

# =============================================================================
# 1. 建立認證檔案 (htpasswd)
# =============================================================================
setup_auth() {
    log "建立認證檔案..."

    # 安裝 htpasswd 工具
    if ! command -v htpasswd &> /dev/null; then
        apt-get update && apt-get install -y apache2-utils
    fi

    # 建立 htpasswd 檔案
    mkdir -p /etc/nginx/conf.d
    htpasswd -Bbn "$REGISTRY_USER" "$REGISTRY_PASSWORD" > /etc/nginx/conf.d/.htpasswd

    log "認證檔案已建立: /etc/nginx/conf.d/.htpasswd"
    log "帳號: $REGISTRY_USER"
}

# =============================================================================
# 2. 設定 Nginx
# =============================================================================
setup_nginx() {
    log "設定 Nginx..."

    # 複製配置
    cp /home/wooo/momo_pro_system/config/nginx/sites-available/registry /etc/nginx/sites-available/

    # 啟用網站
    ln -sf /etc/nginx/sites-available/registry /etc/nginx/sites-enabled/

    # 測試並重載
    nginx -t && systemctl reload nginx

    log "Nginx 配置完成"
}

# =============================================================================
# 3. 申請 SSL 證書
# =============================================================================
setup_ssl() {
    log "申請 SSL 證書..."

    if [[ -f "/etc/letsencrypt/live/$DOMAIN/fullchain.pem" ]]; then
        log "SSL 證書已存在"
        return
    fi

    # 先用 HTTP 配置
    cat > /tmp/registry-http.conf << 'EOF'
server {
    listen 80;
    server_name registry.wooo.work;

    location /.well-known/acme-challenge/ {
        root /var/www/certbot;
    }

    location / {
        return 301 https://$host$request_uri;
    }
}
EOF

    cp /tmp/registry-http.conf /etc/nginx/sites-available/registry
    ln -sf /etc/nginx/sites-available/registry /etc/nginx/sites-enabled/
    nginx -t && systemctl reload nginx

    # 申請證書
    certbot certonly --webroot -w /var/www/certbot -d "$DOMAIN" --non-interactive --agree-tos --email admin@wooo.work

    # 恢復完整配置
    cp /home/wooo/momo_pro_system/config/nginx/sites-available/registry /etc/nginx/sites-available/
    nginx -t && systemctl reload nginx

    log "SSL 證書申請完成"
}

# =============================================================================
# 4. 啟動 Registry
# =============================================================================
start_registry() {
    log "啟動 Docker Registry..."

    cd /home/wooo/registry
    docker compose up -d

    # 等待啟動
    sleep 5

    # 健康檢查
    if curl -s http://127.0.0.1:5000/v2/ | grep -q "{}"; then
        log "Registry 啟動成功"
    else
        error "Registry 啟動失敗"
    fi
}

# =============================================================================
# 5. 測試
# =============================================================================
test_registry() {
    log "測試 Registry..."

    # 登入測試
    echo "$REGISTRY_PASSWORD" | docker login "$DOMAIN" -u "$REGISTRY_USER" --password-stdin

    # 推送測試映像
    docker pull alpine:latest
    docker tag alpine:latest "$DOMAIN/test/alpine:latest"
    docker push "$DOMAIN/test/alpine:latest"

    # 拉取測試
    docker rmi "$DOMAIN/test/alpine:latest"
    docker pull "$DOMAIN/test/alpine:latest"

    # 清理
    docker rmi "$DOMAIN/test/alpine:latest"

    log "Registry 測試通過！"
}

# =============================================================================
# 主程式
# =============================================================================
main() {
    echo ""
    echo "=========================================="
    echo "  Docker Registry 安裝"
    echo "=========================================="
    echo ""

    # 檢查 root
    if [[ $EUID -ne 0 ]]; then
        error "請使用 root 執行: sudo $0"
    fi

    # 建立目錄
    mkdir -p /home/wooo/registry
    cp -r /home/wooo/momo_pro_system/docker/registry/* /home/wooo/registry/

    setup_auth
    setup_ssl
    setup_nginx
    start_registry
    test_registry

    echo ""
    echo "=========================================="
    echo "  安裝完成！"
    echo "=========================================="
    echo ""
    echo "Registry URL: https://$DOMAIN"
    echo "帳號: $REGISTRY_USER"
    echo "密碼: $REGISTRY_PASSWORD"
    echo ""
    echo "使用方式:"
    echo "  docker login $DOMAIN"
    echo "  docker push $DOMAIN/wooo/momo-pro-system:latest"
    echo ""
}

# 執行
main "$@"
