#!/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 commands for maven-installer-plugin"
  echo "for Maven clover-idea-libs/pom.xml file."
  echo "Next copy these dependencies into clover-idea-libs/pom.xml, maven-installer-plugin section."
  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/.*\///'`
    echoCommand $groupId $artifactId $version $libFile
  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
        echoCommand $groupId $artifactId $version $pluginFile
      done
    fi
  done
}

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

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

echoCommand() {
  groupId=$1
  artifactId=$2
  version=$3
  file=$4

  echo "<execution>"
  echo "    <id>install-idea-$artifactId</id><phase>install</phase><goals><goal>install-file</goal></goals>"
  echo "    <configuration>"
  echo "        <file>$file</file><packaging>jar</packaging><generatePom>true</generatePom>"
  echo "        <groupId>$groupId</groupId><artifactId>$artifactId</artifactId><version>$version</version>"
  echo "    </configuration>"
  echo "</execution>"
}

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

echoCommandStart
scanLibraries $1 $2
scanPlugins $1 $2
echoCommandEnd
