#!/bin/sh

IPES_FILE="ipes-amd64-onecloud.sh"
IPES_BASE_PATH="/usr/local/galaxy"
IPES_TAR_PKG=${IPES_BASE_PATH}/ipes-linux-amd64-onecld-latest.tar.gz

mv ${IPES_BASE_PATH}/tool/wget /usr/bin/
mv ${IPES_BASE_PATH}/tool/tar /usr/bin/
mv ${IPES_BASE_PATH}/tool/crontab /usr/bin/
chmod 755 /usr/bin/wget /usr/bin/tar /usr/bin/crontab 

STORAGE_PATH=""
# 寻找所有的/storage[0-9]目录
for path in $(ls -d /storage* | grep storage)
do
    STORAGE_PATH="${STORAGE_PATH} ${path} "
done

echo "storage:"${STORAGE_PATH}
BIN_PATH="/storage"
if [ -d "/storage0" ]; then
    BIN_PATH="/storage0"
fi

if [ -d "/iqiyi_data" ]; then
    BIN_PATH="/iqiyi_data"
fi

config() {
    CONF_PATH=${BIN_PATH}/ipes/var/db/ipes/happ-conf/custom.yml
    echo "args:" > ${CONF_PATH}
    for path in ${STORAGE_PATH}
    do
        echo "  - '${path}'" >> ${CONF_PATH}
    done
    
}

while [ 0 -lt 1 ]
do
    if [ -f "${BIN_PATH}/ipes/bin/ipes" ]; then
        config
        cd ${BIN_PATH}; ./ipes/bin/ipes start
        sleep 30
        ipes_pids=$(ps -ef | grep -w "ipes" | grep -v grep | awk '{print $2}')
        if [ "${ipes_pids}" ];then
            break
        fi
    fi
    
    rm -rf ${BIN_PATH}/ipes
    rm -f ${BIN_PATH}/${IPES_FILE}
    cp ${IPES_BASE_PATH}/${IPES_FILE} ${BIN_PATH}
    cd ${BIN_PATH}; /bin/sh ${IPES_FILE} -p ${STORAGE_PATH} &
    sleep 120
    ipes_pids=$(ps -ef | grep -w "ipes" | grep -v grep | awk '{print $2}')
    if [ "${ipes_pids}" ];then
        break
    fi

    rm -rf ${BIN_PATH}/ipes
    tar xzf ${IPES_TAR_PKG} -C ${BIN_PATH}
    config
    cd ${BIN_PATH}; ./ipes/bin/ipes start
    sleep 30
    ipes_pids=$(ps -ef | grep -w "ipes" | grep -v grep | awk '{print $2}')
    if [ "${ipes_pids}" ];then
        break
    fi
    exit
done

sleepTime=600
# 10分钟检测一次，如果ipes happ:vod 进程有一个不存在则退出容器，等待agent重新拉起
while [ 0 -lt 1 ]
do
        sleep $sleepTime
        ipes_pids=$(ps -ef | grep -w "ipes" | grep -v grep | awk '{print $2}')
        happ_pids=$(ps -ef | grep "happ:vod" | grep -v grep | awk '{print $2}')
        if [ -z "${ipes_pids}" -o -z "${happ_pids}" ]; then
                exit
        fi
done
