#!/bin/sh -e
#
# ipfs 安装脚本

set -e
cd `dirname $0`

FILE_IPFS_CRON="ipfs"
MODULE="ipfs"
AUTHOR="megaops"
PREFIX="/tmp"   #安装路径
PREFIX_CONF="/cyfs/vood/ipfs/etc"   #安装路径
PREFIX_DIR="/cyfs/vood/ipfs"   #安装路径
PREFIX_LOG="/cyfs/vood/ipfs/log"   #日志路径

FILE_INFO="info.txt" #包信息描述文件
FILE_SVC_CTL="service_ctl.sh" #服务启/停控制脚本
PACKAGE="data.tar.bz2" #程序包 data.tar.gz
DAEMON="ipfs"
MAIN_EXE=$DAEMON
DIR_SCRIPT="script"
LOG_SET_TIME=true

COLOR_DFT='\033[0m'
COLOR_BRT='\033[0;1m'
COLOR_RED='\033[0;31m'
COLOR_GREEN='\033[0;32m'
COLOR_YELLOW='\033[1;33m'
COLOR_BLUE='\033[1;34m'

UTIL_FILENAME=`basename $0 2> /dev/null` || UTIL_FILENAME="unistor"
UTIL_MODE=${UTIL_FILENAME}

KEEPLOG=true
LOG_FILE=/var/log/${UTIL_FILENAME}.log
# default params
LOG_DIR="/var/log/shell_util"

TRIM_HEAD_SPACE()
{
    # trim字符串头部的 white space
    echo $1 | sed -r s/"^[[:space:]]+"/""/
}

MD5_CALC()
{
    # $1 filename
    # return md5 of a file
    md5sum $1 | awk -F " " '{print $1}'
}

GET_CONF_ITEM()
{
    # linux config item get
    # $1 filename
    # $2 key
    # return value
    local file="$1"
    local key="$2"
    if [ ! -f "${file}" ]; then
        PERROR "<$FUNCNAME> file '$file' not exist"
        return 1
    fi
    local value=$(cat ${file} |grep -P "^${key}[ ]*=" |awk -F "[=]" '{print $2}'|tail -n 1)
    echo $(TRIM_HEAD_SPACE "${value}")
    # modified by n16111 2018-11-14 17:48:47： support "key = value" (allow spaces around '=')
    # modified by n16111 2019-8-6 15:56:44： return last key's value if multi keys with same name exist
}


# get version
VERSION="$(GET_CONF_ITEM ${FILE_INFO} 'version')"

#  --------- Common Functions -------------

WRITE_LOG(){
    # Log writer, append '[YYYY-mm-dd HH:MM:SS]$1$2$3,...' to  ${LOG_FILE}
    # $1,$2,... strings to be append
    if ${LOG_SET_TIME}; then
        echo "["$(date +"%Y-%m-%d %H:%M:%S")"][${UTIL_MODE}] "$@"" >> ${LOG_FILE}
    else
        echo "[${UTIL_MODE}]  "$@"" >> ${LOG_FILE}
    fi
}

# Format print and log record
PRINT(){
    #  Print to stdout and log file, started by '[$UTIL_MODE]'
    #  $1 $2 $3,... strings to be printed.
    echo -e "[${UTIL_MODE}]" "$@"
    if  ${KEEPLOG} ; then
        WRITE_LOG "$*"
    fi;
}

PERROR(){
    #  Print to stdout and log file with RED font, started by '[$UTIL_MODE]ERROR:'
    #  $1 $2 $3,... strings to be printed.
    echo -e "[${UTIL_MODE}]${COLOR_RED}" "ERROR:" "$@" "${COLOR_DFT}" 1>&2
    if ${KEEPLOG} ; then
        WRITE_LOG "ERROR: $*"
    fi;
}

PWARN(){
    #  Print to stdout and log file with YELLOW font, started by '[$UTIL_MODE]WARNING:'
    #  $1 $2 $3,... strings to be printed.
    echo -e "[${UTIL_MODE}]${COLOR_YELLOW}" "WARNING:" "$@" "${COLOR_DFT}"  1>&2
    if ${KEEPLOG} ; then
        WRITE_LOG "WARNING: $*"
    fi;
}


PSUCCESS(){
    # Print to stdout and log file with 'brighter' effect, started by '[$UTIL_MODE]'
    # $1 $2 $3,... strings to be printed.
    echo -e "[${UTIL_MODE}]${COLOR_BRT}" "$@" "${COLOR_DFT}"
    if ${KEEPLOG} ; then
        WRITE_LOG "$*"
    fi;
}

PINFO(){
    # Print to stdout and log file with 'brighter' effect, started by '[$UTIL_MODE]'
    # $1 $2 $3,... strings to be printed.
    echo -e "[${UTIL_MODE}]${COLOR_BRT}" "$@" "${COLOR_DFT}"
    if ${KEEPLOG} ; then
        WRITE_LOG "$*"
    fi;
}


PBLUE(){
    # Print to stdout and log file with BLUE font, started by '[$UTIL_MODE]'
    # $1 $2 $3,... strings to be printed.
    echo -e "[${UTIL_MODE}]${COLOR_BLUE}" "$@" "${COLOR_DFT}"
    if ${KEEPLOG} ; then
        WRITE_LOG "$*"
    fi;
}


# -- Basic Info --
echo ""
PRINT "-----------------------------------"
PBLUE "module: ${MODULE}"
PRINT "version:${VERSION}"
PRINT "author:${AUTHOR}"
PRINT "package:${PACKAGE}"
PRINT "install prefix:${PREFIX}"
PRINT "-----------------------------------"


upgrade="false"

while getopts 'h::u' OPT; do
    case $OPT in
        u) upgrade="true";;
    esac
done


# -- Pre-Install--
# module是否已安装
if which $MAIN_EXE; then #
    if $(which $MAIN_EXE |grep ${PREFIX}); then #在/opt下
        PWARN "service exist: `which ipfs`"
        sleep 1
        PRINT "service ${MODULE} stop"
        bash service_ctl.sh stop
    else
        if [ "${upgrade}" != "true" ]; then
            PERROR "module '${MAIN_EXE}' already exist in system: $(which $MAIN_EXE) [line:${LINENO}]"
            PERROR "Please uninstall '${MODULE}' and try again !"
            PRINT "installation stopped."
            exit 2;
        fi
    fi
fi


md5_read=`GET_CONF_ITEM $FILE_INFO "md5"`
md5_calc=`MD5_CALC ${PACKAGE}`
PRINT "md5_read: $md5_read"
PRINT "md5_calc: $md5_calc"
if [ "$md5_read" != "$md5_calc" ]; then
    PERROR "MD5 check failed！"
    exit 3
fi

mkdir -p ${PREFIX}/${MODULE}/
#mkdir -p ${PREFIX}/${MODULE}/etc/

if [ ! -d ${PREFIX_CONF} ];then
    mkdir -p ${PREFIX_CONF}
fi

if [ ! -d ${PREFIX_LOG} ];then
    mkdir -p ${PREFIX_LOG}
fi

# -- Installing--
PRINT "decompress package ..."
tar -xvf  ${PACKAGE} -C ${PREFIX}/${MODULE}/ #2> ${ERROR_LOG} > /dev/null 2>&1
ret=$?
if [ "$ret" = "0" ] ; then
    PRINT "decompression complete!"
else
    PERROR "Package Decompress failed! status code = $ret"
    exit 4;
fi

# ipfs 配置文件创建

cp -f $FILE_INFO ${PREFIX_DIR}
cp -f ${PREFIX}/${MODULE}/script/ipfs/check-ipfs.sh /usr/bin/check-ipfs.sh
cp -f ${PREFIX}/${MODULE}/etc/ipfs/systemd/* /lib/systemd/system/
cp -f ${PREFIX}/${MODULE}/etc/ipfs/config.json ${PREFIX_CONF}
cp -f ${PREFIX}/${MODULE}/ipfs_space ${PREFIX_DIR}



systemctl daemon-reload
systemctl disable ${MODULE}
systemctl enable ${MODULE}
# systemd init
if [ "${upgrade}" = "true" ]; then # 若为升级安装，则不启动服务
    PINFO "upgrade installation complete."
    exit 0; ############ TR
else
    # 启动服务
    PINFO "starting service ${MODULE}..."
    systemctl restart ${MODULE}.service
    ret=$?
    if [ "$ret" = "0" ]; then
        PINFO "systemctl started."
     else
        PERROR "systemctl start failed code = $ret"
        PRINT "installation stopped."
        exit 1
    fi
fi

# install ipfs to /etc/cron.d
if [ -f "/etc/cron.d/${FILE_IPFS_CRON}" ]; then
    rm -f /etc/cron.d/${FILE_IPFS_CRON}
fi
echo "SHELL=/bin/bash" > /etc/cron.d/${FILE_IPFS_CRON}
echo "PATH=/sbin:/bin:/usr/sbin:/usr/bin" >> /etc/cron.d/${FILE_IPFS_CRON}
echo "" >> /etc/cron.d/${FILE_IPFS_CRON}
echo '*/1 *    * * *   root  /bin/bash /usr/bin/check-ipfs.sh' >> /etc/cron.d/${FILE_IPFS_CRON}
chmod 644 /etc/cron.d/${FILE_IPFS_CRON}


# -- Complete --
PINFO "installation complete."
