#!/bin/bash

function check_docker_install_status() {
    log_info "Check docker.service install status."
    docker --version &>/dev/null || DOCKER_INSTALL_STATUS=1
    cat /etc/group | awk -F ":" '{print $1}' | grep docker && DOCKER_INSTALL_STATUS=0 || DOCKER_INSTALL_STATUS=1
}

function check_docker_run_status() {
    log_info "Check docker.service is running or not."
    systemctl status docker | grep running &>/dev/null || DOCKER_RUN_STATUS=1
}

function config_daemon_json() {
    DAEMON_FILE=Template/daemon.json.temp
    if [ -f "${DAEMON_FILE}" ]; then
        sed -i /bip/d "${DAEMON_FILE}"
        sed -i "1a\ \"bip\": \"${DOCKER0_NETWORK}\"," ${DAEMON_FILE}
        sed -i /default-address-pools/d ${DAEMON_FILE}
        sed -i "2a\ \"default-address-pools\": [{\"base\":\"${DOCKER_GWBRIDGE_NETWORK}\",\"size\":24}]," ${DAEMON_FILE}
        sed -i /data-root/d ${DAEMON_FILE}
        sed -i "3a\ \"data-root\": \"${DOCKER_DATA_ROOT}\"," ${DAEMON_FILE}
        sed -i /^$/d ${DAEMON_FILE}
        NUM=$(($(wc -l ${DAEMON_FILE} | awk '{print $1}') - 1))
        sed -i "${NUM}s/\,$//g" ${DAEMON_FILE}
    else
        cat >${DAEMON_FILE} <<EOF
{
 "insecure-registries": ["192.168.251.150","192.168.251.78"],
 "bip": "${DOCKER0_NETWORK}",
 "default-address-pools": [{"base":"${DOCKER_GWBRIDGE_NETWORK}","size":24}],
 "data-root": "${DOCKER_DATA_ROOT}"
}
EOF
    fi
}

function docker_ce_install() {
    mkdir -p /etc/docker
    cp Template/daemon.json.temp /etc/docker/daemon.json

    cp Install_Packages/docker-*.rpm /tmp/
    rpm -ivh /tmp/docker-*.rpm
    chmod +x /usr/bin/docker*
    if [ $? -ne 0 ]; then
        log_error "docker install failed !!!"
        exit 1
    else
        log_info "docker install success !!!"
        rm -rf /tmp/docker-*.rpm
    fi
    
    systemctl daemon-reload && systemctl enable docker && systemctl start docker
}

function docker_install() {
    config_daemon_json
    check_docker_install_status

    if [ "${DOCKER_INSTALL_STATUS}" == 1 ]; then
        log_info "install docker-ce"
        docker_ce_install
        unset DOCKER_INSTALL_STATUS
    else
        log_warning "Docker is already installed."
        log_error "In order to achieve the desired effect,please uninstall docker."
        exit 1
    fi

    check_docker_run_status
    if [ "${DOCKER_RUN_STATUS}" == 1 ]; then
        systemctl enable docker
        systemctl start docker
        unset DOCKE_RUN_STATUS
    fi
}
