import argparse
import subprocess
import os
import re

# Delete the specified analysis from the specified hub.
def del_analysis(hubaddr, analysis_id):
    curl_cmd = ['curl']

    def check_page(url):
        args = ['-o', os.devnull, '-w', '%{http_code}', url]
        http_code = subprocess.check_output(curl_cmd + args)
        return (int(http_code.strip())==200)

    analysis_html_url = f'{hubaddr}/analysis/{analysis_id}.html'

    # The relative URL to POST to is shown in the "action" attribute
    # of the "remove_analysis_form" form: extract it from there.
    analysis_dl = subprocess.Popen(curl_cmd + [analysis_html_url],
                                   stdout=subprocess.PIPE)
    analysis_page = analysis_dl.communicate()[0].decode()

    projpage_match = re.search(r'<form\s+name="remove_analysis_form"\s+method="POST"\s+action="([^"]*)">',
                               analysis_page)
    if projpage_match is None:
        print('Could not get analysis page', analysis_html_url)
        print('This is probably because of one of the following:')
        print('- you do not have ANALYSIS_READ permission for the analysis, or')
        print('- there is no such analysis.')
        exit(1)

    project_html_url = f'{hubaddr}{projpage_match.group(1)}'
    # Make sure the Project page is accessible, otherwise there is no
    # point trying to POST to it.
    if not check_page(project_html_url):
        print('Could not get project page', project_html_url)
        print('Make sure you have PROJECT_READ permission for this project.')
        exit(1)

    delete_args = ['-L',
                   '--cookie-jar','cookies.txt',
                   '-d', f'remove_analysis_id={analysis_id}',
                   project_html_url]
    subprocess.check_call(curl_cmd + delete_args)

    if check_page(analysis_html_url):
        print('Could not delete analysis', analysis_id)
        print('Make sure you have ANALYSIS_DELETE permission for the analysis.')
        exit(1)


# Set up.
def go():
    parser = argparse.ArgumentParser(
        description=('Delete an analysis from a CodeSonar hub,'
                     + 'as specified by the command-line arguments.'))
        
    parser.add_argument("hub",
                        help="The hub URL.")
    parser.add_argument("aid",
                        help="The analysis ID for the analysis to delete.")
    args = parser.parse_args()

    allargs = (args.hub, args.aid)
    if not any([a is None for a in allargs]):
        del_analysis(*allargs)

go()
