#!/bin/bash
function log() {
   message="[Docker-Install Log]: $1 "
   echo -e "${message}" 2>&1
}

#Install docker & docker-compose
##Install Latest Stable Docker Release
if which docker >/dev/null; then
   log "检测到 Docker 已安装，跳过安装步骤"
   log "启动 Docker "
   sudo systemctl start docker 2>&1
else
   if [[ -d docker ]]; then
      log "... 离线安装 docker"
      cp docker/bin/* /usr/bin/
      cp docker/service/docker.service /etc/systemd/system/
      chmod +x /usr/bin/docker*
      chmod 754 /etc/systemd/system/docker.service
      log "... 启动 docker"
      sudo systemctl start docker 2>&1

   else
      log "... 在线安装 docker"
      curl -fsSL https://get.docker.com -o get-docker.sh 2>&1
      sudo sh get-docker.sh --mirror Aliyun 2>&1
      log "... 启动 docker"
      sudo systemctl start docker 2>&1
   fi

fi

# 检查docker服务是否正常运行
docker ps 1>/dev/null 2>/dev/null
if [ $? != 0 ];then
   log "Docker 未正常启动，请先安装并启动 Docker 服务后再次执行本脚本"
   exit
fi

##Install Latest Stable Docker Compose Release
if which docker-compose >/dev/null; then
   log "检测到 Docker Compose 已安装，跳过安装步骤"
else
   if [[ -d docker ]]; then
      log "... 离线安装 docker-compose"
      cp docker/bin/docker-compose /usr/bin/
      chmod +x /usr/bin/docker-compose
   else
      log "... 在线安装 docker-compose"
      curl -L https://get.daocloud.io/docker/compose/releases/download/1.29.2/docker-compose-`uname -s`-`uname -m` -o /usr/local/bin/docker-compose 2>&1
      chmod +x /usr/local/bin/docker-compose
      ln -s /usr/local/bin/docker-compose /usr/bin/docker-compose
   fi
fi

## login docker hub
# if [[ -d "~/.docker/config.json" ]]; then
#    ## 存在auths关键字，追加配置
#    result=$(cat ~/.docker/config.json|grep "auths:")
#    if [[ "$result" != ""]]; then
#       var='		"registry.cn-hangzhou.aliyuncs.com": {
# 			"auth": "ZG9ja2VyUmVwb3NpdG9yeUAxNTkwODAwMDk4NjA0NDMwOmh1YW5zaS5uZXRAMjAyMQ=="
# 		}'
#       sed -i  's!\("auths": {"\).*!\1'"${var}"'",!g' ~/.docker/config.json
#    else
#       var='	"auths": {
# 		"registry.cn-hangzhou.aliyuncs.com": {
# 			"auth": "ZG9ja2VyUmVwb3NpdG9yeUAxNTkwODAwMDk4NjA0NDMwOmh1YW5zaS5uZXRAMjAyMQ=="
# 		}}'
#       sed -i  's!\({"\).*!\1'"${var}"'",!g' ~/.docker/config.json
#    fi
# else
#    mkdir -p ~/.docker
#    cp docker/.docker/config.json ~/.docker/
# fi

echo "huansi.NET"|docker login --username=dockerRepository@1573908285225295  --password-stdin registry.cn-hangzhou.aliyuncs.com
# 初始化数据库
# ./docker-install-tb.sh
# if [ $? != 0 ];then
#    log "初始化数据库失败。。。。。。"
#    exit
# fi

# 启动服务
# ./docker-start-services.sh
