#!/usr/bin/env bash

set -e

NAME=docker
VERSION="19.03.15"
BIN_DIR=/usr/bin/
IMAGE_HUB=${1:-1.1.1.1:5000}
DATA_ROOT=${2:-/data/docker}

txtbld=$(tput bold)             # Bold
bldred=${txtbld}$(tput setaf 1) # red
bldgre=${txtbld}$(tput setaf 2) # green
bldylw=${txtbld}$(tput setaf 3) # yellow
txtrst=$(tput sgr0)             # Reset
err=${bldred}ERROR${txtrst}
info=${bldgre}INFO${txtrst}
warn=${bldylw}WARNING${txtrst}


# 判断服务是否正常运行
if [[ "$(systemctl is-enabled ${NAME}.service)" != "enabled" ]]
then

    printf "$info: [ ${bldgre}docker-${VERSION}${txtrst} ] 安装中...\n"

    tar axvf ${NAME}-${VERSION}-$(uname -m).tgz -C ${BIN_DIR} >/dev/null

    cat >/etc/systemd/system/${NAME}.service<<EOF
[Unit]
Description=Docker Application Container Engine
Documentation=https://docs.docker.com
After=network-online.target
Wants=network-online.target

[Service]
Type=notify
EnvironmentFile=-/etc/sysconfig/docker
EnvironmentFile=-/etc/sysconfig/docker-storage
EnvironmentFile=-/etc/sysconfig/docker-network
Environment="PATH=/bin:/sbin:/usr/bin:/usr/sbin"
Environment=GOTRACEBACK=crash

ExecStart=/usr/bin/dockerd \$OPTIONS \\
                           \$DOCKER_STORAGE_OPTIONS \\
                           \$DOCKER_NETWORK_OPTIONS \\
                           \$INSECURE_REGISTRY
ExecReload=/bin/kill -s HUP \$MAINPID
Restart=always
RestartSec=5
LimitNOFILE=infinity
LimitNPROC=infinity
LimitCORE=infinity
Delegate=yes
KillMode=process

[Install]
WantedBy=multi-user.target

EOF

    mkdir -p /etc/docker
    cat >/etc/docker/daemon.json<<EOF
{
  "experimental": true,
  "live-restore": true,
  "registry-mirrors": [ "https://ustc-edu-cn.mirror.aliyuncs.com" ],
  "insecure-registries": [ "${IMAGE_HUB}" ],
  "data-root": "${DATA_ROOT}",
  "exec-opts": ["native.cgroupdriver=systemd"],
  "log-opts": {
    "max-size": "500m"
  }
}

EOF
    systemctl enable ${NAME}.service --now >/dev/null 2>/dev/null
else
    printf "$warn: [ ${bldgre}${NAME}-${VERSION}${txtrst} ] 已安装，正常退出~\n"
fi
