#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.


import os, sys
import json


THIS_SCRIPT_DIR = os.path.dirname(__file__)
CREDENTIALS_DIR = os.path.join(THIS_SCRIPT_DIR, "../../../circleci-failure-tracker-credentials")


def write_creds_module(source_filename, destination_filename):

    json_source_path = os.path.join(CREDENTIALS_DIR, source_filename)
    github_token_path = os.path.join(CREDENTIALS_DIR, "github-personal-access-token-repo-read-permissions.txt")
    sqs_queue_url_path = os.path.join(CREDENTIALS_DIR, "aws-sqs-queue-url.txt")

    dest_path = os.path.join("dr_ci_view_refresh", destination_filename)

    with open(json_source_path) as json_fh, open(dest_path, "w") as output_module_fh:

        creds_dict = json.load(json_fh)

        output_module_fh.write('# This file is autogenerated!\n')
        output_module_fh.write('db_hostname = "%s"\n' % creds_dict["db-hostname"])
        output_module_fh.write('db_username = "%s"\n' % creds_dict["db-user"])
        output_module_fh.write('db_password = "%s"\n' % creds_dict["db-password"])
        output_module_fh.write('db_name = "%s"\n' % "loganci")

        with open(github_token_path) as token_fh:
            access_token = token_fh.read().strip()
            output_module_fh.write('repo_read_auth_token = "%s"\n' % access_token)


        with open(sqs_queue_url_path) as fh:
            queue_url = fh.read().strip()
            output_module_fh.write('sqs_queue_url = "%s"\n' % queue_url)


if __name__ == "__main__":

    write_creds_module("database-credentials-remote-mview-refresher.json", "db_config.py")
    write_creds_module("database-credentials-remote.json", "logan_db_config.py")
