#!/bin/bash

# 检测docker是否安装成功;安装失败则继续安装docker;
# docker images|grep REPOSITORY

clear;
su -c "setenforce 0";
cd ~/

RED='\033[1;31m'
BLUE='\033[1;34m'
GREEN='\033[0;32m'
NC='\033[0m'

USER_ROOT=$(pwd);

# shell if判断用法: https://www.cnblogs.com/mch0dm1n/p/5675219.html
if [ ! -f ~/officeData.zip ]; then
    echo -e "\n${RED}officeData.zip未下载,请下载到$USER_ROOT/officeData.zip目录${NC}\n"
    exit 1
fi
if [ ! -f ~/kodoffice.tar ]; then
    echo -e "\n${RED}kodoffice.tar未下载,请下载到$USER_ROOT/kodoffice.tar目录${NC}\n"
    exit 1
fi

sudo wget -O ~/run_office.sh "http://doc.kodcloud.com/tools/office/linux/run_office.sh"
sudo wget -O ~/7z "http://demo.kodcloud.com/app/sdks/archiveLib/bin/7z"
sudo chmod -Rf 777 ./*

sudo rm -Rf /kodoffice
sudo mkdir /kodoffice
sudo chmod -Rf 777 /kodoffice
sudo  ./7z  x ./officeData.zip -o/kodoffice
sudo mv -f /kodoffice/officeData/* /kodoffice
sudo rm -Rf /kodoffice/officeData
sudo chmod -Rf 777 /kodoffice
sudo cp ~/run_office.sh /kodoffice/


kodoffice_auto_start(){
    AUTO_RUN_FIND=$(cat /etc/rc.local | grep kodoffice | wc -l)
    if [ $AUTO_RUN_FIND -ne 2 ];then
        sudo echo -e '\n#kodoffice自启动 \n/kodoffice/run_office.sh \n' >> /etc/rc.local
    fi

    AUTO_RUN_FIND=$(cat /etc/rc.local | grep kodoffice | wc -l)
    if [ $AUTO_RUN_FIND -eq 2 ];then
        echo -e "\n${GREEN}office auto run服务器自启动添加成功！${NC}\n"
    else
        echo -e "\n${RED}office auto run服务器自启动添加失败，请手动添加/kodoffice/run_office.sh脚本到自启动即可 ！${NC}\n"
    fi
}

kodoffice_install(){
    sudo service docker start
    sudo docker images
    OFFICE_IMAGE="$(sudo docker images)"
    OFFICE_IMAGE="$(echo -e "${OFFICE_IMAGE}\n-kodoffice-"|grep kodoffice|wc -l)"
    if [ $OFFICE_IMAGE -gt 1 ];then
        echo "镜像已存在!旧的kodoffice镜像将被移除"
        sudo sudo service docker restart
        sudo docker rmi -f kodoffice4
        sudo docker rmi -f kodoffice
    fi
    echo -e "\n开始载入镜像，需要2分钟左右\n"
    sudo docker load -i kodoffice.tar
    echo -e "导入完成";
    
    # 启动镜像
    kodoffice_auto_start
    sudo sh /kodoffice/run_office.sh;
}

kodoffice_install
#rm -f 7z