#!/usr/bin/env bash

help() {
  echo ""
  echo "Run this script if you want to add new IntelliJ IDEA version."
  echo "This will scan <idea-folder> for libs and plugins and generate a list of dependencies for Maven pom.xml file"
  echo "Next copy these dependencies into clover-idea-all/pom.xml"
  echo ""
  echo "Usage  : $0 <idea-folder> <idea-version>"
  echo "Example: $0 target/extract/idea-IC-141.3058.30 141.3058.30"
  echo ""
}

# $1 idea folder
# $2 idea version
scanLibraries() {
  groupId="org.openclover.idea.libs"
  libDir=$1/lib
  version=$2

  for libFile in $libDir/*.jar; do
    artifactId=`echo $libFile | sed 's/\.jar//' | sed 's/.*\///'`
    echoDependency $groupId $artifactId $version
  done
}

# $1 idea folder
# $2 idea version
scanPlugins() {
  groupId="org.openclover.idea.plugins"
  pluginsDir=$1/plugins
  version=$2
  pluginIncludes="properties devkit"
  for pluginDir in `ls $pluginsDir`; do
    if [ `echo $pluginIncludes | grep -w $pluginDir | wc -l` -ne 0 ]; then
      for pluginFile in `ls $pluginsDir/$pluginDir/lib/$pluginDir*.jar`; do
        pluginFileName=`echo $pluginFile | sed 's/\.jar//' | sed 's/.*\///'`
        artifactId=$pluginFileName
        echoDependency $groupId $artifactId $version
      done
    fi
  done
}

echoDependencyStart() {
  echo "<!-- Generated automatically by $0 -->"
}

echoDependencyEnd() {
  echo "<!-- End of generated by $0 -->"
}


echoDependency() {
  groupId=$1
  artifactId=$2
  version=$3

  echo "<dependency>"
  echo "  <groupId>$groupId</groupId>"
  echo "  <artifactId>$artifactId</artifactId>"
  echo "  <version>$version</version>"
  echo "</dependency>"
}

if [ "$#" -ne 2 ]; then
  help
  exit 1
fi

echoDependencyStart
scanLibraries $1 $2
scanPlugins $1 $2
echoDependencyEnd
