#!/bin/bash

function uninstall_docker_stack() {
    log_info "uninstall docker stack."
    docker stack rm indrive
    sleep 10
    all_stack=$(docker stack ls | awk 'NR!=1{print $1}')
    for sn in ${all_stack[@]}; do
        docker stack rm ${sn}
    done
}

function uninstall_docker_swarm() {
    log_info "uninstall docker swarm and uninstall docker."
    docker_root_dir=$(docker info | awk -F: '/Docker Root Dir:/{gsub(/ /,"",$2);print $2}')
    docker swarm leave --force &>/dev/null
    systemctl stop docker
    rpm -e docker
    rpm -e docker-ce
    eval rm -rf ${docker_root_dir} /etc/docker
    systemctl daemon-reload
}

function clean_temp_data() {
    rm -fr /tmp/*
}

function main() {
    print_msg "
危险操作注意：
    1. 此操作会删除docker stack indrive、middleware、portainer, 以及 卸载安装的docker，及镜像和容器数据存储目录
    2. 确认要删除后，输入 yes 确认执行。"
    
    for (( ; ; )); do
        interactive_input "确认卸载docker? (yes|no)" _input
        case $_input in
        "yes" | "Yes" | "YES" | "y" | "Y")
            log_info "你选择了 Yes, 将卸载docker。"
            uninstall_docker_stack
            uninstall_docker_swarm
            break
            ;;
        "no" | "No" | "NO" | "n" | "N")
            log_info "你选择了 No，将退出脚本执行"
            exit 0
            ;;
        *)
            log_info "你的输入有误，请输入yes or no..."
            continue
            ;;
        esac
    done

}

## 需要在部署失败之后，清理环境，才可以打开下面CONFIG_FILE 配置行，严禁在生产环境执行
# CONFIG_FILE=../deploy-config/all.conf
source ./utils.sh

main
