
## Check Java installation location

sysrun <- function(x){
  w <- getOption("warn")
  options(warn=2)
  if(Sys.info()["sysname"]=='Windows'){
    suppressWarnings(try(j <- shell(paste(x,"2> nul"),intern=T),T))
  }else{ ## for csh, tcsh
    if(grepl("csh",try(system("sh -c 'ps -p $$ -o ppid=' | xargs ps -o comm= -p",intern=T), TRUE))){
      suppressWarnings(try(j <- system(paste('(',x,'> /dev/tty ) >& /dev/null'),intern=T,ignore.stderr=T),T))
    }else{ ## for sh, bash, dash, fish, zsh, etc.
      suppressWarnings(try(j <- system(paste(x,'2> /dev/null'),intern=T,ignore.stderr=T),T))
    }
  }
  options(warn=w)
  return(j)
}

ckgui <- function(w){
  if( .Platform$GUI == "Rgui" && Sys.info()['sysname']=="Windows" ){
    w <- gsub("\033\\[[0-9]{1,3}m","",w)
  }
  invisible(w)
}

ckjava <- function(){
  if(Sys.info()["sysname"]=='Windows'){ ## Windows
    j <- sysrun("where java")
  }else if(Sys.info()["sysname"]=="Darwin"){ ## Mac
    j <- sysrun('ls /Library/Java/JavaVirtualMachines')
    m <- list()
    for(i in j){
      if(grepl("[.]jdk$",tolower(i))){
        k <- paste0('/Library/Java/JavaVirtualMachines/',i,'/Contents/Home')
        m <- append( m, k)  
      }
    }
    m <- unlist(m)
    j <- sysrun('/usr/libexec/java_home -V')
    m <- append( m, grep("^[/]",gsub(".* [/]","/",j),value=TRUE))
    j <- unique(unlist(m))
  }else{ ## Linux
    j <- list()
    j <- append(j,sysrun('ls -1d /usr/lib/jvm/*/|sed "s/\\/$//"'))
    j <- append(j,sysrun("ls -ltr /etc/alternatives/java*|sed 's/.*->[ ]*//'|grep 'bin'|sed 's/\\/bin.*$//'"))
    j <- unique(unlist(j))
  }
  invisible(j)
}

rjenv <- function(){
  n <- 1
  for(i in ckjava()){
    s <- (Sys.info()["sysname"]=='Windows')
    j <- sub("[\\/]bin.*","",i)
    if(s){j <- gsub('[\\]','\\\\\\\\',j); k <- "\\\\bin;"}else{k <- "/bin:"}
    cat(ckgui(paste0("\nJVM condition No.",n,' for \033[36m',i,
                     '\033[31m\n\n## Write it at ".Rprofile" or run it on R at first ##\n\033[32m',
                     ' JH <- "',j,'"',"\n",
                     ' Sys.setenv("JAVA_HOME"=JH)',"\n",
                     ' Sys.setenv("PATH"=paste0(JH,"',k,'",Sys.getenv("PATH")))',"\033[0m\n")))
    if(!s){
      cat(ckgui(paste0('\033[31m## It works as same if you write it on ".Renvilon" ##\033[32m\n',
                       ' JAVA_HOME=',j,'\n PATH=${JAVA_HOME}/bin:${PATH}\033[0m\n')))
    }
    n <- n + 1
  }
  cat("\n")
}

## Check Java installation location
print(ckjava())

## Show R initial file settings for each JDK
rjenv()

