/**
 * Copyright (C) 2014-2015 LinkedIn Corp. (pinot-core@linkedin.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.linkedin.pinot.tools.admin.command;

import java.io.File;
import java.io.FileInputStream;

import org.apache.commons.io.FileUtils;
import org.kohsuke.args4j.Option;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.linkedin.pinot.common.utils.FileUploadUtils;
import com.linkedin.pinot.common.utils.NetUtil;
import com.linkedin.pinot.common.utils.TarGzCompressionUtils;


/**
 * Class for command to upload data into Pinot.
 *
 *
 */
public class UploadSegmentCommand extends AbstractBaseCommand implements Command {
  private static final Logger LOGGER = LoggerFactory.getLogger(UploadSegmentCommand.class);

  @Option(name = "-controllerHost", required = false, metaVar = "<String>", usage = "host name for controller.")
  private String _controllerHost;

  @Option(name = "-controllerPort", required = false, metaVar = "<int>", usage = "Port number for controller.")
  private String _controllerPort = DEFAULT_CONTROLLER_PORT;

  @Option(name = "-segmentDir", required = true, metaVar = "<string>", usage = "Path to segment directory.")
  private String _segmentDir = null;

  @Option(name = "-help", required = false, help = true, aliases = { "-h", "--h", "--help" },
      usage = "Print this message.")
  private boolean _help = false;

  @Override
  public boolean getHelp() {
    return _help;
  }

  @Override
  public String getName() {
    return "UploadSegment";
  }

  @Override
  public String toString() {
    return ("UploadSegment -controllerHost " + _controllerHost + " -controllerPort " + _controllerPort
        + " -segmentDir " + _segmentDir);
  }

  @Override
  public void cleanup() {

  }

  @Override
  public String description() {
    return "Upload the Pinot segments.";
  }

  public UploadSegmentCommand setControllerHost(String controllerHost) {
    _controllerHost = controllerHost;
    return this;
  }

  public UploadSegmentCommand setControllerPort(String controllerPort) {
    _controllerPort = controllerPort;
    return this;
  }

  public UploadSegmentCommand setSegmentDir(String segmentDir) {
    _segmentDir = segmentDir;
    return this;
  }

  @Override
  public boolean execute() throws Exception {
    if (_controllerHost == null) {
      _controllerHost = NetUtil.getHostAddress();
    }

    LOGGER.info("Executing command: " + toString());
    File dir = new File(_segmentDir);
    File[] files = dir.listFiles();

    for (File file : files) {
      File tgzFile = file;
      boolean cleanTmpFile = false;

      if (file.isDirectory()) {
        String srcDir = file.getAbsolutePath();
        String tgzFileName = TarGzCompressionUtils.createTarGzOfDirectory(srcDir);
        tgzFile = new File(tgzFileName);
        cleanTmpFile = true;
      }

      FileUploadUtils.sendSegmentFile(_controllerHost, _controllerPort, tgzFile.getName(),
          new FileInputStream(tgzFile), tgzFile.length());

      // Clean the file if we created it.
      if (cleanTmpFile) {
        FileUtils.deleteQuietly(tgzFile);
      }
    }

    return true;
  }
}

@@ -680,16 +680,182 @@
 mmand;%0A%0A
+import com.linkedin.pinot.common.utils.FileUploadUtils;%0Aimport com.linkedin.pinot.common.utils.NetUtil;%0Aimport com.linkedin.pinot.common.utils.TarGzCompressionUtils;%0A
 import j
@@ -899,16 +899,43 @@
 Stream;%0A
+import java.io.IOException;
 %0Aimport 
@@ -1063,175 +1063,8 @@
 y;%0A%0A
-import com.linkedin.pinot.common.utils.FileUploadUtils;%0Aimport com.linkedin.pinot.common.utils.NetUtil;%0Aimport com.linkedin.pinot.common.utils.TarGzCompressionUtils;%0A%0A
 %0A/**
@@ -1296,16 +1296,136 @@
 .class);
+%0A  private static final String SEGMENT_UPLOADER = %22segmentUploader%22;%0A  private static final String TAR_GZIP = %22.tar.gz%22;
 %0A%0A  @Opt
@@ -3042,24 +3042,256 @@
 s();%0A    %7D%0A%0A
+    // Create a temp working directory.%0A    File tmpDir = File.createTempFile(SEGMENT_UPLOADER, null, FileUtils.getTempDirectory());%0A    FileUtils.deleteQuietly(tmpDir);%0A    tmpDir.mkdir();%0A    FileUtils.forceDeleteOnExit(tmpDir);%0A%0A
     LOGGER.i
@@ -3467,76 +3467,104 @@
 le;%0A
+%0A
       
-boolean cleanTmpFile = false;%0A%0A      if (file.isDirectory()) %7B
+if (file.isDirectory()) %7B%0A        LOGGER.info(%22Compressing segment %7B%7D%22, file.getName());%0A
 %0A   
@@ -3636,16 +3636,28 @@
 leName =
+%0A           
  TarGzCo
@@ -3704,89 +3704,175 @@
 cDir
-);%0A        tgzFile = new File(tgzFileName);%0A        cleanTmpFile = true;%0A      %7D%0A
+, tmpDir + File.separator + file.getName() + TAR_GZIP);%0A        tgzFile = new File(tgzFileName);%0A      %7D%0A%0A      LOGGER.info(%22Uploading segment %7B%7D%22, tgzFile.getName());
 %0A   
@@ -3958,26 +3958,16 @@
 tName(),
-%0A         
  new Fil
@@ -3988,16 +3988,26 @@
 gzFile),
+%0A         
  tgzFile
@@ -4021,127 +4021,8 @@
 ());
-%0A%0A      // Clean the file if we created it.%0A      if (cleanTmpFile) %7B%0A        FileUtils.deleteQuietly(tgzFile);%0A      %7D
 %0A   

Fix for UploadSegmentCommand deleting files it did not create