/**
 * 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 com.linkedin.pinot.common.utils.FileUploadUtils;
import com.linkedin.pinot.common.utils.NetUtil;
import com.linkedin.pinot.common.utils.TarGzCompressionUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.kohsuke.args4j.Option;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


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

  @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();
    }

    // Create a temp working directory.
    File tmpDir = File.createTempFile(SEGMENT_UPLOADER, null, FileUtils.getTempDirectory());
    FileUtils.deleteQuietly(tmpDir);
    tmpDir.mkdir();
    FileUtils.forceDeleteOnExit(tmpDir);

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

    for (File file : files) {
      File tgzFile = file;

      if (file.isDirectory()) {
        LOGGER.info("Compressing segment {}", file.getName());

        String srcDir = file.getAbsolutePath();
        String tgzFileName =
            TarGzCompressionUtils.createTarGzOfDirectory(srcDir, tmpDir + File.separator + file.getName() + TAR_GZIP);
        tgzFile = new File(tgzFileName);
      }

      LOGGER.info("Uploading segment {}", tgzFile.getName());
      FileUploadUtils.sendSegmentFile(_controllerHost, _controllerPort, tgzFile.getName(), new FileInputStream(tgzFile),
          tgzFile.length());
    }

    return true;
  }
}

@@ -903,36 +903,8 @@
 am;%0A
-import java.io.IOException;%0A
 impo
@@ -3212,50 +3212,21 @@
 ();%0A
+%0A
     
-FileUtils.forceDeleteOnExit(tmpDir);%0A%0A
+try %7B%0A  
     
@@ -3274,24 +3274,26 @@
 ing());%0A    
+  
 File dir = n
@@ -3314,24 +3314,26 @@
 ntDir);%0A    
+ 
+ 
 File%5B%5D files
@@ -3349,24 +3349,26 @@
 stFiles();%0A%0A
+  
     for (Fil
@@ -3387,24 +3387,26 @@
 es) %7B%0A      
+  
 File tgzFile
@@ -3417,24 +3417,26 @@
 ile;%0A%0A      
+ 
+ 
 if (file.isD
@@ -3445,24 +3445,26 @@
 ectory()) %7B%0A
+  
         LOGG
@@ -3511,24 +3511,26 @@
 etName());%0A%0A
+  
         Stri
@@ -3569,24 +3569,26 @@
 ();%0A        
+  
 String tgzFi
@@ -3599,20 +3599,8 @@
 me =
-%0A           
  Tar
@@ -3617,16 +3617,31 @@
 ionUtils
+%0A              
 .createT
@@ -3670,16 +3670,34 @@
 , tmpDir
+.getAbsolutePath()
  + File.
@@ -3740,24 +3740,26 @@
 P);%0A        
+  
 tgzFile = ne
@@ -3781,27 +3781,31 @@
 ame);%0A      
+ 
+ 
 %7D%0A%0A
+  
       LOGGER
@@ -3850,24 +3850,26 @@
 getName());%0A
+  
       FileUp
@@ -3877,16 +3877,29 @@
 oadUtils
+%0A            
 .sendSeg
@@ -3996,24 +3996,30 @@
 ,%0A          
+      
 tgzFile.leng
@@ -4025,26 +4025,248 @@
 gth());%0A    
+  %7D%0A    %7D catch (Exception e) %7B%0A      LOGGER.error(%22Exception caught while uploading segment %7B%7D%22, _segmentDir, e);%0A    %7D finally %7B%0A      // Delete the temporary working directory.%0A      FileUtils.deleteQuietly(tmpDir);%0A    
 %7D
-%0A
 %0A    return 

Fix for UploadSegmentCommand deleting files it did not create