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

createNetwork(){
  echo "create new work"
  retVal=$(docker network ls | grep ea_net)
  if [ -n "$retVal" ];then
    echo "create network"
  else
    echo "create network"
    docker network create ea_net;
  fi
}

createNetwork

startMidWare(){
  echo "start mid ware"
  #find . -type d -maxdepth 1 |grep -v apps | while read line;
  ls -d */ |grep -v apps | while read line;
    do
      echo "start ${pwd}/$line";
      cd $line;
      if [ ! -f "docker-compose.yml" ];then
        echo "start ${pwd}/$line";
        # echo "rocketmq";
        cd rmq/
        ./start.sh;
        cd ../;
      else
         docker-compose up -d;
      fi
      cd ../;
    done
}

startApp(){
  echo "start app"
  cd $work_dir/apps;
  ls -d */ | grep -v env | while read line;
      do
        echo "start app $line";
        pwd;
        cd $line;
        docker-compose down;
        docker-compose build;
        docker-compose up -d;
        cd ../;
      done
  cd $work_dir;
}

stopApp(){
  echo "stop app"
  cd $work_dir/apps;
  ls -d */ | grep -v env | while read line;
      do
        echo "start app $line";
        pwd;
        cd $line;
        docker-compose down;
        cd ../;
      done
  cd $work_dir;
}

stopAll(){
  echo "stop all"
  docker ps -a|awk '{print $1}'|tail -n +2 | while read line; do docker stop $line; docker rm $line; done
}

cleanLog(){
  echo "clean log"
  cd $work_dir/apps;
  ls -d */ | grep -v env | while read line;
      do
        echo "clean log $(pwd)/$line/logs";
        rm -rf $line/logs/*;
      done
  cd $work_dir;
  cd $work_dir/rmq; rm -rf logs/*; rm -rf store/*; cd ../;
  cd $work_dir/rmqs; rm -rf logs/*; rm -rf store/*; cd ../;
}

usage(){
  echo "usage: startApp.sh [app|db]"
}

if [ $# -eq 0 ];then
    usage
else
    case "$1" in
        "app")
            startApp
         ;;
        "db")
            startMidWare
          ;;
        "stop")
          stopAll
        ;;
        "clean")
          cleanLog
        ;;
       "usage")
          usage
        ;;
        *)
            usage
        ;;
    esac
fi
