#!/usr/bin/env bash
# 文件名: ansible_startup.sh 
# 功  能： 快速运行 ansible (容器环境)

set -o pipefail

export offline=false
export ssh_key_dir=${HOME}/.ssh
export kubeconfig_dir=${HOME}/.ssh
export container_name=ansible-docker
export image_tag=2.9.13-$(uname -m)
export image_file=ansible-docker-${image_tag}.tar.xz
export image_name=registry.cn-shenzhen.aliyuncs.com/shuhui/ansible-docker:${image_tag}


function deploy_docker() {
 echo ''
}

function generate_ssh_cert() {

    if [[ ! -e "${HOME}/.ssh/ed25519" ]]
    then
        ssh-keygen -a 250 -t ed25519 -N '' -f ${HOME}/.ssh/ed25519 -C "Gitee-Deploy" >/dev/null
        chmod 0600 ${HOME}/.ssh/ed25519
        chattr +i ${HOME}/.ssh/ed25519
        echo "[+] SSH证书创建成功，请将公钥添加至目标主机！"
    fi
}

function import_container_image() {
    docker images | grep ${container_name} >/dev/null
    if [[ "$?" -ne "0" ]]
    then
        if [[ "$offline" = "true" ]]
        then
            if [[ -e "${image_file}" ]]
            then
                tar axvf ${image_file} >/dev/null 2>&1
                cat ${image_file%.*} | docker import - ${image_name}
                echo "[+] ansible-playbook导入成功！"
                rm -rf ${image_file%.*}
            else
                echo "[-] 错误: ${image_file}文件不存在!"
                exit 67
            fi

        else
            docker pull ${image_name} >/dev/null 2>&1
            echo "[+] ansible-playbook拉取成功！"
        fi
    fi
}

function run_ansible_playbook() {

    docker ps -a |grep ${container_name} >/dev/null && docker rm -f ${container_name} >/dev/null 2>&1

    echo "[+] 您已进入 ansible-playbook 容器中，愉快地玩耍吧~"
    docker run -it --name=${container_name} \
                   --rm \
                   --hostname=ansible-in-docker \
                   --entrypoint /bin/bash \
                   --network=host \
                   --privileged \
                   --volume=/sys/fs/cgroup:/sys/fs/cgroup:ro \
                   --volume=/opt:/opt:rw \
                   --volume=/root:/root:rw \
                   --volume=${PWD}:/ansible/playbook:rw \
                   ${image_name}
}

generate_ssh_cert
import_container_image
run_ansible_playbook
