#!/usr/bin/env python3
#
# Cancel a task
#

import optparse
import pscheduler
import urllib


pscheduler.set_graceful_exit()


#
# Gargle the arguments
#


class VerbatimParser(optparse.OptionParser):
    def format_epilog(self, formatter):
        return self.epilog

opt_parser = VerbatimParser(
    usage="Usage: %prog task-url",
    epilog=
"""
Example:

  cancel https://ps.foo.org/pscheduler/task/12345...
      Cancel a task
"""
    )
opt_parser.disable_interspersed_args()

opt_parser.add_option("--bind",
                      help="Make the request from the provided address",
                      default=None,
                      action="store", type="string",
                      dest="bind")

opt_parser.add_option("--key",
                      help="Key required for write access to the task (Optional @/path/to/file)",
                      action="store", type="string",
                      dest="key")



(options, remaining_args) = opt_parser.parse_args()

if len(remaining_args) != 1:
    opt_parser.print_usage()
    pscheduler.fail()

task_url = remaining_args[0]
params = {}

parsed = list(urllib.parse.urlsplit(task_url))

path_parts = parsed[2].split("/")

if (len(path_parts) != 4) \
        or (path_parts[0:3] != ["", "pscheduler", "tasks"]):
    pscheduler.fail("%s: Not a task URL" % task_url)


if options.key is not None:
    try:
        params["key"] = pscheduler.string_from_file(options.key)
    except IOError as ex:
        pscheduler.fail("Unable to read key file: " + str(ex))


status, result = pscheduler.url_delete(task_url, bind=options.bind,
                                       params=params,
                                       throw=False)

if status == 200:
    pscheduler.succeed()
elif status == 404:
    pscheduler.fail("Task not found.")
else:
    pscheduler.fail(result)
