'use strict';

const functions = require('firebase-functions');
const gcs = require('@google-cloud/storage')();
const path = require('path');

const gcsBucketId = `${process.env.GCLOUD_PROJECT}.appspot.com`;
const LOCAL_TMP_FOLDER = '/tmp/';

const BROWSER_CACHE_DURATION = 300;
const CDN_CACHE_DURATION = 600;

function sendStoredFile(request, response) {
  let filePathSegments = request.path.split('/').filter((segment) => {
    // Remove empty leading or trailing path parts
    return segment !== '';
  });

  const version = filePathSegments[0];
  const isDocsPath = filePathSegments[1] === 'docs';
  const lastSegment = filePathSegments[filePathSegments.length - 1];
  const bucket = gcs.bucket(gcsBucketId);

  let downloadSource;
  let downloadDestination;
  let fileName;

  if (isDocsPath && filePathSegments.length === 2) {
    fileName = 'index.html';
    filePathSegments = [version, 'docs', fileName];
  } else {
    fileName = lastSegment;
  }

  downloadSource = path.join.apply(null, filePathSegments);
  downloadDestination = `${LOCAL_TMP_FOLDER}${fileName}`;

  downloadAndSend(downloadSource, downloadDestination).catch(error => {
    if (isDocsPath && error.code === 404) {
      fileName = 'index.html';
      filePathSegments = [version, 'docs', fileName];
      downloadSource = path.join.apply(null, filePathSegments);
      downloadDestination = `${LOCAL_TMP_FOLDER}${fileName}`;

      return downloadAndSend(downloadSource, downloadDestination);
    }

    return Promise.reject(error);
  }).catch(error => {
    let message = 'General error';
    if (error.code === 404) {
      if (fileName.split('.').length === 1) {
        message = 'Directory listing is not supported';
      } else {
        message = 'File not found';
      }
    }

    return response.status(error.code).send(message);
  });

  function downloadAndSend(downloadSource, downloadDestination) {
    return bucket.file(downloadSource).download({
      destination: downloadDestination
    }).then(() => {
      return response.status(200)
        .set({
          'Cache-Control': `public, max-age=${BROWSER_CACHE_DURATION}, s-maxage=${CDN_CACHE_DURATION}`
        })
        .sendFile(downloadDestination);
    });
  }
}

exports.sendStoredFile = functions.https.onRequest(sendStoredFile);

@@ -2222,72 +2222,958 @@
 %0A%7D%0A%0A
-exports.sendStoredFile = functions.https.onRequest(sendStoredFile
+function deleteOldSnapshotZip(event) %7B%0A  const object = event.data;%0A%0A  const bucketId = object.bucket;%0A  const filePath = object.name;%0A  const contentType = object.contentType;%0A%0A  const bucket = gcs.bucket(bucketId);%0A%0A  if (event.eventType === 'providers/cloud.storage/eventTypes/object.change' &&%0A      contentType === 'application/zip' &&%0A      filePath.startsWith('snapshot/')%0A    ) %7B%0A%0A    bucket.getFiles(%7B%0A      prefix: 'snapshot/',%0A      delimiter: '/',%0A      autoPaginate: false%0A    %7D).then(function(data) %7B%0A      const files = data%5B0%5D;%0A%0A      const oldZipFiles = files.filter(file =%3E %7B%0A        return file.metadata.name !== filePath && file.metadata.contentType === 'application/zip';%0A      %7D);%0A%0A      oldZipFiles.forEach(function(file) %7B%0A        file.delete();%0A      %7D);%0A%0A    %7D);%0A  %7D%0A%7D%0A%0Aexports.sendStoredFile = functions.https.onRequest(sendStoredFile);%0Aexports.deleteOldSnapshotZip = functions.storage.object().onChange(deleteOldSnapshotZip
 );%0A

delete old zip files on snapshot