#!/bin/bash
# ============================================
# Docker 容器定时重启一键安装脚本
# 北京时间 早6点 和 晚6点 自动重启所有容器
# ============================================

set -e

echo "🚀 开始安装 Docker 容器定时重启服务..."

# 创建脚本目录
mkdir -p /usr/local/bin

# 创建重启脚本
cat > /usr/local/bin/restart-all-containers.sh << 'EOF'
#!/bin/bash
CONTAINERS=$(/usr/bin/docker ps -q 2>/dev/null)
if [ -n "$CONTAINERS" ]; then
    /usr/bin/docker restart $CONTAINERS
    echo "$(date): Restarted containers: $CONTAINERS" >> /var/log/container-restart.log
else
    echo "$(date): No running containers to restart" >> /var/log/container-restart.log
fi
EOF
chmod +x /usr/local/bin/restart-all-containers.sh

# 创建 systemd service 文件
cat > /etc/systemd/system/restart-containers.service << 'EOF'
[Unit]
Description=Restart all Docker containers
After=docker.service
Requires=docker.service

[Service]
Type=oneshot
ExecStart=/usr/local/bin/restart-all-containers.sh
EOF

# 创建 systemd timer 文件（北京时间 6:00 和 18:00）
cat > /etc/systemd/system/restart-containers.timer << 'EOF'
[Unit]
Description=Timer to restart Docker containers at 6:00 and 18:00 Beijing Time

[Timer]
OnCalendar=*-*-* 06:00:00 Asia/Shanghai
OnCalendar=*-*-* 18:00:00 Asia/Shanghai
Persistent=true

[Install]
WantedBy=timers.target
EOF

# 重新加载 systemd 并启用定时器
systemctl daemon-reload
systemctl enable restart-containers.timer
systemctl start restart-containers.timer

echo ""
echo "✅ 安装完成！"
echo ""
echo "📋 定时器状态："
systemctl status restart-containers.timer --no-pager
echo ""
echo "📅 下次执行时间："
systemctl list-timers restart-containers.timer --no-pager
echo ""
echo "============================================"
echo "常用命令："
echo "  查看状态:   systemctl status restart-containers.timer"
echo "  手动执行:   systemctl start restart-containers.service"
echo "  查看日志:   cat /var/log/container-restart.log"
echo "  停用定时:   systemctl disable --now restart-containers.timer"
echo "============================================"
