# Copyright (C) 2021 The Android Open Source Project
#
# 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.

import flask
import requests

BUCKET_NAME = 'ui.perfetto.dev'

REQ_HEADERS = [
    'Accept',
    'Accept-Encoding',
    'Cache-Control',
]

RESP_HEADERS = [
    'Content-Type',
    'Content-Encoding',
    'Content-Length',
    'Cache-Control',
    'Date',
    'ETag',
    'Last-Modified',
    'Expires',
]

# Cache-control response header for everything but index.html.
CACHE_CONTROL = 'public, max-age=3600, no-transform'

# Cache-control response header for index.html.
CACHE_CONTROL_INDEX_HTML = 'no-cache, no-transform'

app = flask.Flask(__name__)


# Redirect v1.2.3 to v.1.2.3/
@app.route('/v<int:x>.<int:y>.<int:z>')
def version_redirect(x, y, z):
  return flask.redirect('/v%d.%d.%d/' % (x, y, z), code=302)


# Serve the requests from the GCS bucket.
@app.route('/', methods=['GET'])
@app.route('/<path:path>', methods=['GET'])
def main(path=''):
  path = '/' + path
  path += 'index.html' if path.endswith('/') else ''

  # If the HTTP client didn't ask for compression, pass it to the requests
  # module so it doesn't automatically try to use gzip encoding.
  req_headers = {'Accept-Encoding': 'identity'}
  for key in set(flask.request.headers.keys()).intersection(REQ_HEADERS):
    req_headers[key] = flask.request.headers.get(key)

  url = 'https://commondatastorage.googleapis.com/' + BUCKET_NAME + path
  req = requests.get(url, headers=req_headers, stream=True)
  if (req.status_code != 200):
    return flask.abort(req.status_code)

  req.raw.decode_content = False
  # Note: content_raw will possibly be gzipped if the request headers passed
  # 'Accept-Encoding: gzip'.
  content_raw = req.raw.read()
  resp = flask.Response(content_raw)
  for key in set(req.headers.keys()).intersection(RESP_HEADERS):
    resp.headers[key] = req.headers.get(key)
  if path.endswith('/index.html'):
    resp.headers['Cache-Control'] = CACHE_CONTROL_INDEX_HTML
  else:
    resp.headers['Cache-Control'] = CACHE_CONTROL
  return resp


if __name__ == '__main__':
  # This is used when running locally only.
  app.run(host='127.0.0.1', port=10000, debug=True)
