#!/bin/sh
work_dir=$(cd `dirname $0`;pwd)

images=(redis:7.2.4
redis:6.2.1
openjdk:11-jdk
nacos/nacos-server:v2.3.2
nacos/nacos-mysql:5.7
adminer:latest
postgres:13
nginx:1.21-alpine
lscr.io/linuxserver/openssh-server:latest
foxiswho/rocketmq:4.8.0
styletang/rocketmq-console-ng:latest
docker.elastic.co/elasticsearch/elasticsearch:7.10.2
)

checkAndCreateWorkDir(){
  if [ ! -d $work_dir/offlineImage ];then
    mkdir -p $work_dir/offlineImage
    cd $work_dir/offlineImage
  fi
}
checkAndCreateWorkDir


printImage(){
  echo "print images"
  for i in "${images[@]}";do
    echo $i
  done
}

pullImage(){
  echo "pull images"
  for i in "${images[@]}";do
    nohup docker pull $i >>offlineImage.log 2>&1  &
  done
}

checkImage(){
  echo "check images"
  for i in "${images[@]}";do
    # docker images | awk '{print $1":"$2}'| grep $i
    retVal=$(docker images | awk '{print $1":"$2}'| grep $i)
    if [ $? -ne 0 ];then
      echo "no images $i"
    fi
  done
}

saveImage(){
  echo "save images"
  nohup docker save -o ea_base_img.tar "${images[@]}" >> offlineImage.log 2>&1  &
}

loadImage(){
  echo "load images"
  if [ ! -f ea_base_img.tar ];then
    echo "no ea_base_img.tar"
    exit 1
  else
    echo "load ea_base_img.tar"
    nohup docker load -i ea_base_img.tar >>offlineImage.log 2>&1  &
  fi
}

usage(){
  echo "Usage: Offline Image "
  echo "Usage: ./offlineImage.sh usage|print|save|load|pull"
}

if [ $# -eq 0 ];then
    usage
else
    case "$1" in
        "print")
          printImage
         ;;
        "check")
          checkImage
        ;;
        "save")
          saveImage
        ;;
		    "load")
          loadImage
        ;;
		    "pull")
          pullImage
        ;;
        *)
            usage
        ;;
    esac
fi