#!/bin/sh
func() {
    echo "Usage:"
    echo "install.sh [-s wx_storage_path] [-i wx_install_path] [-d download_url] [-l local_path]"
    exit -1
}
while getopts ':h:s:i:d:l:' OPT; do
    case $OPT in
        s) STORAGE_PATH="$OPTARG";;
        i) INSTALL_PATH="$OPTARG";;
        d) DOWNLOAD_URL="$OPTARG";;
        l) LOCAL_TAR="$OPTARG";;
        h) func;;
        ?) func;;
    esac
done

if [[ -z "$STORAGE_PATH" ||  ! -d "$STORAGE_PATH" ]];then
    echo "storage_path must be provided and must be directory "
    exit 1
fi
if [[ -z "$INSTALL_PATH" ||  ! -d "$STORAGE_PATH" ]];then
    echo "install_path must be provided and must be directory"
    exit 1
fi

if [[ -z "$DOWNLOAD_URL"  &&  -z "$LOCAL_TAR" ]];then
    echo "download_url or local_path must be provided "
    exit 1
fi
export STORAGE_PATH=${STORAGE_PATH}
export INSTALL_PATH=${INSTALL_PATH}


WXEDGE_PATH="$INSTALL_PATH/xyapp/miner.plugin-wxedge.ipk"
mkdir -p $WXEDGE_PATH
if [[ ! -z  "$DOWNLOAD_URL" ]];then 
    wget -qO-  $DOWNLOAD_URL | tar -xz -C $WXEDGE_PATH
else
    LOCAL_TAR=`readlink -f ${LOCAL_TAR}`
    tar  -xzf ${LOCAL_TAR}  -C ${WXEDGE_PATH}
fi

chmod +x -R $WXEDGE_PATH

sed -i "s#WXEDGE_INSTALL_PATH#${WXEDGE_PATH}#g"  $WXEDGE_PATH/wxedge

# sed -i "/^export STORAGE_PATH= /c export STORAGE_PATH=${STORAGE_PATH}"   $WXEDGE_PATH/wxedge.sh
# sed -i "/^export INSTALL_PATH= /c export INSTALL_PATH=${INSTALL_PATH}"   $WXEDGE_PATH/wxedge.sh

if [ -f /etc/init.d/wxedge.sh ]; then
    rm /etc/init.d/wxedge.sh 
fi

if [[ -z "$WXEDGE_PATH" && -d "$WXEDGE_PATH" ]]; then
    rm -rf $WXEDGE_PATH/*
fi
mv  $WXEDGE_PATH/wxedge /etc/init.d/
/etc/init.d/wxedge enable
cd $WXEDGE_PATH; sh start.sh  >/dev/null 2>&1 &















