#!/usr/bin/env python
#
# You should set the GITTOKEN environment variable
# to an access token for gitlab.cern.ch
#
# This script retrieves the full list of projects
# for a given group, creates a build token for each
# and then sets a secure variable for the project
# with the name TDAQ_CI_TOKEN.
#
import sys
import os
import requests
import json
import string
from pprint import pprint

url = 'https://gitlab.cern.ch/api/v3/'
token = os.environ['GITTOKEN']
project = len(sys.argv) > 1 and sys.arv[1] or 'atlas-tdaq-software'

headers = { 'PRIVATE-TOKEN': token}

group = requests.get(url + 'groups/%s' % project, headers=headers).json()

for prj in group["projects"]:
    print prj['name'],
    token = requests.post(url + 'projects/%d/triggers' % prj['id'], headers=headers).json()
    if token.has_key('token'):
        requests.post(url + 'projects/%d/variables' % prj['id'], headers=headers, 
                      params={ 'key': 'TDAQ_CI_TOKEN', 'value': token['token'] })
    
