#!/bin/bash
SOURCE="$0"
while [ -h "$SOURCE"  ]; do # resolve $SOURCE until the file is no longer a symlink
    DIR="$( cd -P "$( dirname "$SOURCE"  )" && pwd  )"
    SOURCE="$(readlink "$SOURCE")"
    [[ $SOURCE != /*  ]] && SOURCE="$DIR/$SOURCE" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located
done
DIR="$( cd -P "$( dirname "$SOURCE"  )" && pwd  )"

if [ -z $WORKSPACE ];then
    echo "WORKSPACE not exists"
else
    set DIR=$WORKSPACE
fi

echo "current dir"
echo "$DIR"

cd "$DIR"
projectname=$(basename `pwd`)

npm run parking-build

if [ -d "$DIR/dist" ];then

  cd "$DIR/dist"

  # copy module.json
  cp ../module.json ./

  # package
  VERSION=$(cat ../.version)
  lastdir=../release/
  if [ -d ${lastdir} ];then
    echo "删除旧release文件夹"
    rm -rf ${lastdir}
  else
    echo "文件夹不存在！"
  fi
  mkdir -p ${lastdir}

  dir=../release/nerv/$projectname/$VERSION
  mkdir -p ${dir}
  tar -zcvf "${dir}/$projectname-$VERSION.tgz" ./*

  templatedir=../release/resources/templates/nerv/$projectname/$VERSION/$projectname
  mkdir -p ${templatedir}
  cp -r ../resources/templates/* ${templatedir}

  cd ../

  releasefile=nerv-$projectname-$VERSION.tgz
  if [ -f ${releasefile} ];then
    echo "删除旧包！"
    rm -rf ${releasefile}
  fi

  tar -zcvf ${releasefile} ./release/* release.yaml

  mkdir -p ./release/nervui
  cp -r ./release/nerv/* ./release/nervui

  if [ -f ${releasefile} ];then
    echo "编译成功！"
    mv ${releasefile} ./release
  else
    echo "编译失败!!!"
    exit 1
  fi

else
  echo "编译失败!!!"
  exit 1
fi
