/*
 * Copyright 2000-2012 JetBrains s.r.o.
 *
 * 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 jetbrains.buildServer.agent.android.tools;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
import jetbrains.buildServer.util.FileUtil;
import org.jetbrains.annotations.NotNull;

public class ApkUtil {
  @NotNull
  public static File addFileToApk(@NotNull final File tempDir,
                                  @NotNull final File file,
                                  @NotNull final File apk,
                                  @NotNull final String relativePath) throws IOException {
    final File tempApk = FileUtil.createTempFile(tempDir, "", ".apk", true);

    final ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(tempApk));
    try {
      final ZipFile sourceApk = new ZipFile(apk);
      try {
        final Enumeration<? extends ZipEntry> entries = sourceApk.entries();
        while (entries.hasMoreElements()) {
          final ZipEntry entry = entries.nextElement();
          try {
            zos.putNextEntry(new ZipEntry(entry.getName()));
            if (!entry.isDirectory()) {
                FileUtil.copy(sourceApk.getInputStream(entry), zos);
            }
          }
          finally {
            zos.closeEntry();
          }
        }
      }
      finally {
        sourceApk.close();
      }

      try {
        zos.putNextEntry(new ZipEntry(relativePath));
        final FileInputStream fis = new FileInputStream(file);
        try {
          FileUtil.copy(fis, zos);
        }
        finally {
          fis.close();
        }
      }
      finally {
        zos.closeEntry();
      }
    }
    finally {
      zos.close();
    }

    return tempApk;
  }
}
