#!/bin/bash
# 用法: ./add-docker-registry.sh <registry_address>
# 示例: ./add-docker-registry.sh 222.211.217.80:50080

set -e

if [ $# -ne 1 ]; then
    echo "Usage: $0 <registry_address>"
    exit 1
fi

REGISTRY="$1"
DAEMON_JSON="/etc/docker/daemon.json"

# 如果 daemon.json 不存在，则创建一个基本结构
if [ ! -f "$DAEMON_JSON" ]; then
    echo "{}" | sudo tee "$DAEMON_JSON" > /dev/null
fi

# 读取现有 insecure-registries，如果没有就初始化为空数组
EXISTING=$(jq -r '.["insecure-registries"] // []' "$DAEMON_JSON")

# 检查是否已经存在
if echo "$EXISTING" | grep -qx "$REGISTRY"; then
    echo "Registry $REGISTRY already exists in daemon.json."
else
    # 添加到 insecure-registries 数组
    UPDATED=$(echo "$EXISTING" | jq --arg r "$REGISTRY" '. + [$r]')
    # 写回 daemon.json
    sudo jq --argjson r "$UPDATED" '.["insecure-registries"] = $r' "$DAEMON_JSON" | sudo tee "$DAEMON_JSON" > /dev/null
    echo "Added registry $REGISTRY to daemon.json."
fi

# 重启 Docker
sudo systemctl daemon-reload
sudo systemctl restart docker
echo "Docker restarted successfully."

