#!/bin/sh

source /etc/profile

## 应用名称
APP_NAME=nk-cloud-config

## 工作目录
APP_WS=/home/nk_cloud/config
CONTAINER_WS=/home/nk_cloud/config
## 镜像版本
VERSION=2.1

## 公司名称
corporation=northking

## 镜像仓库配置
DOCKER_REGISTRY=192.168.0.165:8889
USERNAME=admin
PASSWORD=admin123


## 获取运行 容器ID
RUN_ID=$(docker ps |grep ${APP_NAME}|awk '{print $1}')

## 停止旧的容器
if [ "${RUN_ID}" = "" ]; then
  echo "Container ${APP_NAME} is not starting "
else
  ## 停止 docker容器
  docker stop ${RUN_ID}
  echo "Container ${APP_NAME} , ID: ${RUN_ID} is stopped   "
 fi

## 获取  docker 容器ID
STOP_ID=$(docker ps -a |grep ${APP_NAME}|awk '{print $1}')

## 删除旧的容器
if [ "${STOP_ID}" = "" ]; then
  echo "Container ${APP_NAME} is not exist"
else
  ## 移除 docker容器
  docker rm ${STOP_ID}
  echo "Remove container ${APP_NAME} , ID: ${STOP_ID}  "
 fi

## 获取  镜像ID
IMG_ID=$(docker images |grep ${APP_NAME}|awk '{print $3}')

## 删除本地镜像
if [ "${IMG_ID}" = "" ]; then
  echo "Image ${APP_NAME} is not exist "
else
  ## 移除 docker镜像
  docker rmi ${IMG_ID}
  echo "Remove image ${APP_NAME} , ID: ${IMG_ID}  "
 fi


## 删除镜像
docker rmi ${DOCKER_REGISTRY}/${corporation}/${APP_NAME}:${VERSION}
docker rmi ${corporation}/${APP_NAME}:${VERSION}


## 登录镜像仓库
docker login -u ${USERNAME} -p ${PASSWORD} ${DOCKER_REGISTRY}

## 下载镜像
docker pull ${DOCKER_REGISTRY}/${corporation}/${APP_NAME}:${VERSION}

## 启动镜像
docker run -itd --net=host --restart=always \
                           --name ${APP_NAME} \
                           --privileged=true \
                           -v /etc/localtime:/etc/localtime \
                           -v ${APP_WS}:${CONTAINER_WS} \
                           ${DOCKER_REGISTRY}/${corporation}/${APP_NAME}:${VERSION}
