<commit_before>package se.gigurra.dcs.remote

import java.io.File
import java.nio.file.{Files, StandardOpenOption}

import com.twitter.io.Charsets
import se.gigurra.serviceutils.twitter.logging.Logging

import scala.util.{Failure, Success, Try}

/**
  * Created by kjolh on 4/11/2016.
  */
object ScriptInstaller extends Logging {

  val srcFiles = Seq(
    "dcs_remote.lua",
    "dcs_remote_net_utils.lua",
    "dkjson.lua"
  )

  val exportLuaFileName = "Export.lua"

  def apply(): Unit = Try {

    logger.info(s"Installing dcs remote lua scripts -> DCS ..")

    val sources = srcFiles.map(fileName => fileName -> resource2String(s"lua/$fileName"))
    val exportLuaLine = resource2String(s"lua/$exportLuaFileName").lines.toSeq.head

    val homeDir = getHomeDir
    val saveGamesDir = ensureSavedGamesDir(homeDir)
    val defaultDcsDir = ensureDefaultDcsDir(saveGamesDir)
    val dcsDirs = ensureDcsDirs(saveGamesDir, defaultDcsDir)

    for (dcsDir <- dcsDirs) {
      logger.info(s" --> Installing dcs remote into: $dcsDir")
      val ScriptsDir = ensureScriptsDir(dcsDir)
      ensureExportsLuaContent(exportLuaLine, ensureExportsLuaFile(ScriptsDir))
      ensureScriptFiles(sources, ScriptsDir)
    }

  } match {
    case Success(_) =>
    case Failure(e) =>
      logger.error(e, s"Unable to auto-install lua scripts for Dcs-Remote into DCS")
  }

  def ensureDcsDirs(saveGamesDir: File, defaultDcsDir: File): Set[File] = {
    logger.info(s"Looking for 'Saved Games/DCS' directories ..")
    saveGamesDir.listFiles().filter(_.isDirectory).filter(_.getName.startsWith("DCS")).toSet ++ Set(defaultDcsDir)
  }

  def getHomeDir: String = {
    logger.info(s"Looking for home directory ..")
    val homeDir = System.getProperty("user.home")
    if (homeDir == null)
      throw new RuntimeException(s"Unable to find user's home dir")
    logger.info(s"Found home dir at $homeDir")
    homeDir
  }

  def ensureDefaultDcsDir(saveGamesDir: File): File = {
    val defaultDcsDir = new File(s"$saveGamesDir/DCS")
    if (!defaultDcsDir.exists() && !defaultDcsDir.mkdir())
      throw new RuntimeException(s"Unable to create dcs default dir")
    defaultDcsDir
  }

  def ensureSavedGamesDir(homeDir: String): File = {
    val saveGamesDir = new File(s"$homeDir/Saved Games")
    if (!saveGamesDir.exists())
      throw new RuntimeException(s"Unable to find user's Saved Games dir")
    saveGamesDir
  }

  def ensureScriptFiles(sources: Seq[(String, String)], ScriptsDir: File): Unit = {
    logger.info(s"Adding script files")
    for ((fileName, desiredContents) <- sources) {
      val trgFile = new File(s"$ScriptsDir/$fileName")
      var needsOverwrite = true
      if (trgFile.exists()) {
        val prevContents = file2String(trgFile)
        if (prevContents == desiredContents)
          needsOverwrite = false
      } else {
        if (!trgFile.createNewFile())
          throw new RuntimeException(s"Could not create script file $trgFile")
      }

      if (needsOverwrite) {
        logger.info(s"Need to update $trgFile, doing it ..")
        Files.write(trgFile.toPath, desiredContents.getBytes(Charsets.Utf8), StandardOpenOption.WRITE)
      } else {
        logger.info(s"No need to update $trgFile ..")
      }

    }
  }

  def ensureExportsLuaContent(exportLuaLine: String, trgExportLuaFile: File): Any = {
    logger.info(s"Adding entry to Export.lua if not already there ..")
    val prevContents = file2String(trgExportLuaFile)
    if (prevContents.contains(exportLuaLine)) {
      logger.info(s"No need to append Export.lua - Dcs Remote entry already there")<commit_msg>Improved code for getting savedGamesFolder<commit_after>package se.gigurra.dcs.remote

import java.io.File
import java.nio.file.{Files, StandardOpenOption}

import com.sun.jna.platform.win32.{Guid, Shell32}
import com.sun.jna.ptr.PointerByReference
import com.twitter.io.Charsets
import se.gigurra.serviceutils.twitter.logging.Logging

import scala.util.{Failure, Success, Try}

/**
  * Created by kjolh on 4/11/2016.
  */
object ScriptInstaller extends Logging {

  val srcFiles = Seq(
    "dcs_remote.lua",
    "dcs_remote_net_utils.lua",
    "dkjson.lua"
  )

  val exportLuaFileName = "Export.lua"

  def apply(): Unit = Try {

    logger.info(s"Installing dcs remote lua scripts -> DCS ..")

    val sources = srcFiles.map(fileName => fileName -> resource2String(s"lua/$fileName"))
    val exportLuaLine = resource2String(s"lua/$exportLuaFileName").lines.toSeq.head
    val defaultDcsDir = ensureDefaultDcsDir(savedGamesFolder)
    val dcsDirs = ensureDcsDirs(savedGamesFolder, defaultDcsDir)

    for (dcsDir <- dcsDirs) {
      logger.info(s" --> Installing dcs remote into: $dcsDir")
      val ScriptsDir = ensureScriptsDir(dcsDir)
      ensureExportsLuaContent(exportLuaLine, ensureExportsLuaFile(ScriptsDir))
      ensureScriptFiles(sources, ScriptsDir)
    }

  } match {
    case Success(_) =>
    case Failure(e) =>
      logger.error(e, s"Unable to auto-install lua scripts for Dcs-Remote into DCS")
  }

  def ensureDcsDirs(saveGamesDir: File, defaultDcsDir: File): Set[File] = {
    logger.info(s"Looking for 'Saved Games/DCS' directories ..")
    saveGamesDir.listFiles().filter(_.isDirectory).filter(_.getName.startsWith("DCS")).toSet ++ Set(defaultDcsDir)
  }

  lazy val savedGamesFolder: File = {
    val guid = Guid.GUID.fromString("4C5C32FF-BB9D-43b0-B5B4-2D72E54EAAA4")
    val ptrByRef = new PointerByReference()
    val result = Shell32.INSTANCE.SHGetKnownFolderPath(guid, 0, null, ptrByRef)
    if (result.intValue() == 0)
      new File(ptrByRef.getValue.getWideString(0))
    else
      throw new RuntimeException(s"Failed to find Saved Games folder")
  }

  def ensureDefaultDcsDir(saveGamesDir: File): File = {
    val defaultDcsDir = new File(s"$saveGamesDir/DCS")
    if (!defaultDcsDir.exists() && !defaultDcsDir.mkdir())
      throw new RuntimeException(s"Unable to create dcs default dir")
    defaultDcsDir
  }

  def ensureScriptFiles(sources: Seq[(String, String)], ScriptsDir: File): Unit = {
    logger.info(s"Adding script files")
    for ((fileName, desiredContents) <- sources) {
      val trgFile = new File(s"$ScriptsDir/$fileName")
      var needsOverwrite = true
      if (trgFile.exists()) {
        val prevContents = file2String(trgFile)
        if (prevContents == desiredContents)
          needsOverwrite = false
      } else {
        if (!trgFile.createNewFile())
          throw new RuntimeException(s"Could not create script file $trgFile")
      }

      if (needsOverwrite) {
        logger.info(s"Need to update $trgFile, doing it ..")
        Files.write(trgFile.toPath, desiredContents.getBytes(Charsets.Utf8), StandardOpenOption.WRITE)
      } else {
        logger.info(s"No need to update $trgFile ..")
      }

    }
  }

  def ensureExportsLuaContent(exportLuaLine: String, trgExportLuaFile: File): Any = {
    logger.info(s"Adding entry to Export.lua if not already there ..")
    val prevContents = file2String(trgExportLuaFile)
    if (prevContents.contains(exportLuaLine)) {
      logger.info(s"No need to append Export.lua - Dcs Remote entry already there")
{'fraction_non_alphanumeric': 0.11455412226584408, 'fraction_numerical': 0.006870443073471677, 'mean_word_length': 3.6078811369509043, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 15, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2558161', 'n_tokens_mistral': 2405, 'n_tokens_neox': 2336, 'n_words': 513}