#!/usr/bin/env python3
import json, os, sys
import requests
api_url = "https://copr.fedorainfracloud.org/api_2"
api_login = os.environ["copr_login"]
api_token = os.environ["copr_token"]

r = requests.get("%s/projects/%s/chroots" % (api_url, os.environ["copr_projectid"])).json()
chroots = []
for i in r.get("chroots"):
    chroots.append(i.get("chroot").get("name"))

metadata = {
    'chroots': chroots,
    'project_id': int(os.environ["copr_projectid"]),
}
files = {
    "srpm": (os.path.basename(sys.argv[1]), open(sys.argv[1], 'rb'), 'application/x-rpm'),
    "metadata": ('', json.dumps(metadata))
}
r = requests.post("%s/builds" % api_url, auth=(api_login, api_token), files=files)

@@ -27,17 +27,17 @@
 ort 
-json, os,
+os%0Aimport
  sys
@@ -178,16 +178,63 @@
 _token%22%5D
+%0Aproject_id = int(os.environ%5B%22copr_projectid%22%5D)
 %0A%0Ar = re
@@ -285,105 +285,131 @@
 rl, 
-os.environ%5B%22copr_
 project
+_
 id
-%22%5D)).json()%0Achroots = %5B%5D%0Afor i in r.get(%22chroots%22):
+))%0Aif not r.ok:%0A    print(r.json().get(%22message%22, %22Error returned, but no message%22))
 %0A    
-chroots.append(
+sys.exit(1)%0A%0Achroots = %5B
 i.ge
@@ -435,249 +435,696 @@
 me%22)
-)%0A%0Ametadata = %7B%0A    'chroots': chroots,
+ for i in r.json().get(%22chroots%22)%5D%0A%0Agh_url = %22https://api.github.com/repos/%7B%7D/%7B%7D/releases/latest%22.format(%0A    os.environ%5B%22CIRCLE_PROJECT_USERNAME%22%5D,%0A    os.environ%5B%22CIRCLE_PROJECT_REPONAME%22%5D%0A)%0Agh = requests.get(gh_url)%0Aif not gh.ok:
 %0A    
-'
 pr
-oject_id': int(os.environ%5B%22copr_projectid%22%5D),%0A%7D%0Afiles = %7B%0A    %22srpm%22: (os.path.basename(sys.argv%5B1%5D), open(sys.argv%5B1%5D, 'rb'), 'application/x-rpm'),%0A    %22metadata%22: ('', json.dumps(metadata))
+int(%22Failed to fetch latest Github release%22)%0A    print(gh.json())%0A    sys.exit(1)%0A%0Aassets = gh.json().get(%22assets%22)%0Aif len(assets) %3E 1:%0A    print(%22More than 1 asset uploaded to Github, unexpected%22)%0A    sys.exit(1)%0Aasset = assets%5B0%5D.get(%22browser_download_url%22)%0Aif not asset.endswith(%22.src.rpm%22):%0A    print(%22Github asset is not a .src.rpm%22)%0A    sys.exit(1)%0A%0Ametadata = %7B%0A    'chroots': chroots,%0A    'project_id': project_id,%0A    'srpm_url': asset,
 %0A%7D%0A
+%0A
 r = 
@@ -1159,16 +1159,34 @@
 api_url,
+%0A                 
  auth=(a
@@ -1210,18 +1210,207 @@
 en),
- files=files
+%0A                  json=metadata)%0Aif r.status_code != 201:%0A    print(r.json().get(%22message%22, %22Error returned, but no message%22))%0A    sys.exit(1)%0Aprint(%22Build started at %7B%7D%22.format(r.headers%5B%22Location%22%5D)
 )%0A

Fix copr build trigger script