#!/bin/bash
# ---------------------------------------------------------------------------
#  Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#  http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.

if [ "$(uname)" == "Darwin" ]
then
    CURRENT_PATH=$(dirname "$0")
else
    CURRENT_PATH="$(dirname "$(readlink -f "$0")")"
fi

\cp $CURRENT_PATH/ballerina-command-1.5.1/lib/ballerina-command-1.5.1.jar $CURRENT_PATH/../lib

if [ $? -ne '0' ]; then
  echo "error occurred while copying ballerina jar"
  # remove if copied with an error.
  if [ -f "$CURRENT_PATH/../lib/ballerina-command-1.5.1.jar" ]; then
        rm -rf $CURRENT_PATH/../lib/ballerina-command-1.5.1.jar
  fi
  exit $?
fi

\cp $CURRENT_PATH/ballerina-command-1.5.1/bin/bal $CURRENT_PATH/../bin

if [ $? -ne '0' ]; then
  echo "error occurred while copying ballerina file."
  # remove already copied jar.
  if [ -f "$CURRENT_PATH/../lib/ballerina-command-1.5.1.jar" ]; then
        rm -rf $CURRENT_PATH/../lib/ballerina-command-1.5.1.jar
  fi
  exit $?
fi

echo "Tool version updated to the latest version: 1.5.1"
echo "Cleaning old files..."

for file in $CURRENT_PATH/../lib/*; do
    if [ -f "$file" ] && [[ "$file" == *ballerina-command*.jar ]] && [[ "$file" != *ballerina-command-1.5.1.jar ]]; then
	rm -rf $file
    fi
done
