import groovy.xml.MarkupBuilder
import java.util.regex.*
import java.util.zip.*
import java.io.*
import com.jetbrains.plugin.blockmap.core.BlockMap
import com.jetbrains.plugin.blockmap.core.FileHash
import com.fasterxml.jackson.databind.ObjectMapper

buildscript {
    repositories {
       mavenCentral()
    }
    dependencies {
       classpath group: 'org.jetbrains.intellij', name: 'blockmap', version: '1.0.5'
       // https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind
       classpath group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.12.3'
    }
}

defaultTasks 'installMps'

allprojects {
  apply plugin: 'java'

  repositories {
    mavenLocal()
    mavenCentral()
  }

  // please no jars, no manifests, no build folders
  jar { onlyIf { false } }
}

repositories {
  ivy {
      url 'https://teamcity.jetbrains.com/guestAuth/repository/download'
      patternLayout {
        ivy '[module]/[revision]/teamcity-ivy.xml'
        artifact '[module]/[revision]/[revision].[ext]'
      }
  }
}

configurations {
    mps
}

dependencies {
  // MPS-related stuff declared as project properties
  mps "org:${mpsBuildConfiguration}:${mpsBuildNumber}:${mpsBuildLabel}.tcbuildtag@zip"
}

task installMps(type: Copy)  {
  onlyIf {
    ! file('MPS_HOME').exists()
  }

  from zipTree(configurations.mps[0])
  into 'MPS_HOME'

  // Gradle woodoo for unzipping an archive
  eachFile { FileCopyDetails fcp ->
    // copy the contents of the directory named "MPS ${mpsRelease}"
    if (fcp.relativePath.pathString.startsWith("MPS ${mpsRelease}/")) {
      // remap the file to the root
      def segments = fcp.relativePath.segments
      def pathsegments = segments[1..-1] as String[]
      fcp.relativePath = new RelativePath(!fcp.file.isDirectory(), pathsegments)

    } else {
      fcp.exclude()
    }
    // avoid overriding files
    if (fcp.relativePath.getFile(destinationDir).exists()) {
       it.exclude()
    }
  }
  includeEmptyDirs = false
}

task deleteMps(type: Delete) {
  delete 'MPS_HOME'
}
