#!/usr/bin/env sh

SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )

echo "Upgrading Rancher Shell"

# Get the version number from the package.json file
VERSION=$(node -p -e "require('${SCRIPT_DIR}/package.json').version")

echo "Updating to version: ${VERSION}"
echo ""

FORCE="false"

if [ "$1" == "-f" ]; then
  FORCE="true"
fi

# Check for a clean git repository
if [ ! -d ".git" ] && [ "${FORCE}" == "false" ]; then
  echo "Not runnning in a git repository. Re-run with -f to ignore this check"
  echo "Note: This action will update yuor files - running in a git repsository will ensure you have visibility over changes made"
  exit 1 
fi

if [[ $(git diff --stat) != '' ]] && [ "${FORCE}" == "false" ]; then
  echo "Git repository is not clean. Re-run with -f to ignore this check"
  echo "Note: This action will update yuor files - running in a clean git repsository will ensure you have visibility over changes made"
  exit 1 
fi

# Check this is a Rancher Extension
if [ ! -f "./package.json" ]; then
  echo "Can't find package.json - check you're running from the correct folder"
  exit 1 
fi

HAS_SHELL=$(grep "\"@rancher/shell\"" package.json -c )
if [ "${HAS_SHELL}" != "1" ]; then
  echo "package.json does not reference @rancher/shell - check you're running from the correct folder"
  exit 1 
fi

# Copy files for the top-level folder (from the app creator)
rsync --exclude nuxt.config.js ${SCRIPT_DIR}/app/files/* .

# Go through each folder in the pkg folder and update their files
for pkg in ./pkg/*
do
  if [ -d "${pkg}" ]; then
    pkgName=$(basename $pkg)
    echo "Updating package ${pkgName}"

    cp ${SCRIPT_DIR}/pkg/files/* ${pkg}
  fi
done
