#!/bin/bash
#

docker_pkg="../Install_Packages/docker-20.10.5-1.el7.x86_64.rpm"

function remove() {
    arry=(containerd containerd-shim ctr docker docker-compose dockerd docker-init docker-proxy runc)

    command docker 2>/dev/null

    if [ $? -ne 0 ]; then
        echo "docker not install"
        exit 101
    fi

    if [[ $docker_pkg =~ "docker" ]] && [[ $docker_pkg =~ "rpm" ]]; then
        if [ ! -f $docker_pkg ]; then
            echo "docker path not exist."
            exit 101
        fi
    fi

    vers=$(dockerd --version | awk '{print $3}')
    ver=$(echo ${vers%%.*})

    if [ $ver -gt 18 ]; then
        systemctl stop containerd docker 2>/dev/null
        rpm -qa | grep -q docker

        if [ $? -eq 0 ]; then
            rpm -e docker 2>/dev/null
            rpm -e docker-ce 2>/dev/null
            rpm -e docker-containerd.io 2>/dev/null
        else
            for i in ${arry[@]}; do
                rm -f /usr/bin/$i
            done
            grep -q 'docker' /etc/group && groupdel docker
            rm -f /usr/lib/systemd/system/{containerd.service,docker.service,docker.socket}
        fi
    else
        systemctl stop docker 2>/dev/null
        rpm -qa | grep -q docker

        if [ $? -eq 0 ]; then
            rpm -e docker-ce 2>/dev/null
            rpm -e docker-containerd.io 2>/dev/null
            rpm -e docker 2>/dev/null
        else
            rm -f /usr/bin/docker*
            rm -f /usr/lib/systemd/system/docker.service
        fi
    fi

    systemctl daemon-reload
}

function upgrade() {
    rpm --install $docker_pkg 2>/dev/null && {
        echo "upgrade docker success."
        systemctl restart containerd docker
    } || echo 'upgrade docker failed.'
}

remove
upgrade
