/**
 * Copyright 2018 The AMP HTML Authors. All Rights Reserved.
 *
 * 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.
 */

'use strict';

const express = require('express');
const path = require('path');
const app = express();
const AmpSsrMiddleware = require('amp-toolbox-optimizer-express');
const ampSSR = require('amp-toolbox-optimizer');
const compression = require('compression');
const httpProxy = require('http-proxy');
const https = require('https');
const runtimeVersion = require('amp-toolbox-runtime-version');
const PreloadImagesTransformer = require('./lib/PreloadImagesTransformer');
const GoogleFontsPreconnectTransformer = require('./lib/GoogleFontsPreconnectTransformer');
const apicache = require('apicache');

const cache = apicache.middleware;

// Configure the transformers to be used.
// otherwise a default configuration is used.
ampSSR.setConfig({
  transformers: [
    new PreloadImagesTransformer(),
    'AddAmpLink',
    'ServerSideRendering',
    'RemoveAmpAttribute',
    // needs to run after ServerSideRendering
    'AmpBoilerplateTransformer',
    // needs to run after ServerSideRendering
    'ReorderHeadTransformer',
    // needs to run after ReorderHeadTransformer
    'RewriteAmpUrls',
    new GoogleFontsPreconnectTransformer()
  ]
});

const target = process.argv[2] || 'https://www.ampbyexample.com'
//
// Create a HTTP Proxy server with a HTTPS target
//
const proxy = httpProxy.createProxyServer({
  agent: https.globalAgent,
  changeOrigin: true,
  target: target,
  headers: {
    'accept-encoding': 'none'
  }
});

proxy.on('error', (err, req, res) => {
  res.writeHead(404, {
    'Content-Type': 'text/plain'
  });

  res.end('Page not Found');
});

const staticMiddleware = express.static(path.join(__dirname, '/public'));

// Cache pags for 20 mins
app.use(cache('20 minutes'));

// Enable compression
app.use(compression());

const currentVersion = () => runtimeVersion.currentVersion();
app.use(AmpSsrMiddleware.create({
  ampSsr: ampSSR,
  runtimeVersion: currentVersion
}));
app.use(staticMiddleware);
app.use((req, res) => {
  proxy.web(req, res);
});

const port = process.env.PORT || 8080;
app.listen(port);
console.log(`Proxying ${target} on port ${port}`);

@@ -677,38 +677,8 @@
 ');%0A
-const path = require('path');%0A
 cons
@@ -705,18 +705,24 @@
 onst Amp
-Ss
+Optimize
 rMiddlew
@@ -778,19 +778,25 @@
 onst amp
-SSR
+Optimizer
  = requi
@@ -1338,19 +1338,25 @@
 sed.%0Aamp
-SSR
+Optimizer
 .setConf
@@ -1759,24 +1759,88 @@
 ()%0A  %5D%0A%7D);%0A%0A
+// Read proxy for command line, or default to ampbyexample.com.%0A
 const target
@@ -1891,19 +1891,18 @@
 ple.com'
+;
 %0A
-//
 %0A// Crea
@@ -1928,28 +1928,19 @@
 ver 
-with a HTTPS
+the
  target%0A
 //%0Ac
@@ -1939,11 +1939,8 @@
 get%0A
-//%0A
 cons
@@ -2068,42 +2068,207 @@
     
-'accept-encoding': 'none'%0A  %7D%0A%7D);%0A
+// We force encoding to avoid issues with data decompression.%0A    'accept-encoding': 'none'%0A  %7D%0A%7D);%0A%0A// http-proxy doesn't handle errors by default, and crashes the server. Se we add our own handler.
 %0Apro
@@ -2404,108 +2404,25 @@
 );%0A%0A
-const staticMiddleware = express.static(path.join(__dirname, '/public'));%0A%0A// Cache pags for 20 mins
+// Enable caching
 %0Aapp
@@ -2492,24 +2492,54 @@
 ession());%0A%0A
+// Enable versioned AMP urls.%0A
 const curren
@@ -2587,16 +2587,53 @@
 rsion();
+%0A%0A// Enable the Optimizer middleware.
 %0Aapp.use
@@ -2636,18 +2636,24 @@
 .use(Amp
-Ss
+Optimize
 rMiddlew
@@ -2674,19 +2674,31 @@
  amp
-Ssr: ampSSR
+Optimizer: ampOptimizer
 ,%0A  
@@ -2737,34 +2737,46 @@
 ));%0A
-app.use(staticMiddleware);
+%0A// Handle requests through the proxy.
 %0Aapp

Rename to AmpOptimizer