#!/usr/bin/env python3

import sys
import json
import os

ZIP_EXTENSION = ".zip"

def get_file_name(path, name, type):
    return path + '/' + name + type

def generate_install_script(plugins_json_file, output_file):
    """Generate the plugin installation script from plugins JSON file"""
    with open(plugins_json_file) as pf:
        plugins_object = json.load(pf)

    with open(output_file, 'w+') as of:
        of.write('#!/usr/bin/env sh \n')

        confluentHubPlugins = plugins_object['ConfluentHubPlugins']
        if confluentHubPlugins is not None:
            for plugin in confluentHubPlugins:
                of.write(f"confluent connect plugin install {plugin['Name']} --force --worker-configurations /dev/null --plugin-directory /mnt/plugins {plugin['ExtraArgs']} \n")

        urlPlugins = plugins_object['RemoteURLPlugins']
        if urlPlugins is not None:
            for plugin in urlPlugins:
                filename = get_file_name("/mnt/plugins", plugin['Name'], ZIP_EXTENSION)
                force_curl = plugin.get('ForceCurl', False)
                curl_extra_args = plugin.get('CurlExtraArgs', '')
                wget_extra_args = plugin.get('WgetExtraArgs', '')

                if force_curl:
                    # Force curl usage
                    of.write(f"echo '===> Using curl (force curl enabled) to download {plugin['Name']}' \n")
                    # download file using curl. set "--max-redirs 0" for CVE-2021-31879
                    # Note: --max-redirs 0 means no redirects, so -L flag is not needed/conflicts
                    of.write(f"curl --max-redirs 0 \"{plugin['ArchivePath']}\" -o {filename} {curl_extra_args} \n")
                else:
                    # Try wget first, fallback to curl on failure
                    of.write(f"echo '===> Attempting to download {plugin['Name']} using wget' \n")
                    # download file. set "--max-redirect 0" for CVE-2021-31879
                    of.write(f"if ! wget --max-redirect 0 \"{plugin['ArchivePath']}\" -O {filename} {wget_extra_args}; then \n")
                    of.write(f"  echo '===> wget failed, falling back to curl for {plugin['Name']}' \n")
                    # Note: --max-redirs 0 means no redirects, so -L flag is not needed/conflicts
                    of.write(f"  curl --max-redirs 0 \"{plugin['ArchivePath']}\" -o {filename} {curl_extra_args} \n")
                    of.write(f"fi \n")

                # verify checksum
                sha512filename = get_file_name("/mnt/plugins", plugin['Name'], '.sha512')
                of.write(f"echo {plugin['Checksum']} {filename} > {sha512filename} \n")
                of.write(f"sha512sum --check {sha512filename} \n")
                of.write(f"rm -f {sha512filename} \n")

                # install with confluent-cli
                of.write(f"confluent connect plugin install {filename} --force --worker-configurations /dev/null --plugin-directory /mnt/plugins {plugin['ExtraArgs']} \n")
                of.write(f"rm -vf {filename} \n")
    os.chmod(output_file, 0o755)

if __name__ == '__main__':
    plugins_json_file = sys.argv[1]
    output_file = sys.argv[2]
    generate_install_script(plugins_json_file, output_file)
