#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Florian Lambert <florian.lambert@cycloid.io>
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

import sys
import argparse
import logging as log
import json
import requests
import yaml

VERSION = '1.0'

PARSER = argparse.ArgumentParser(description='Refresh pipeline Cycloid.io')

PARSER.add_argument("-u", "--username",
                    required=True,
                    type=str,
                    help='Username')
PARSER.add_argument("-p", "--password",
                    required=True,
                    type=str,
                    help='Password')
PARSER.add_argument("-i", "--insecure",
                    action='store_true')
PARSER.add_argument("-t", "--pipeline-template",
                    required=True,
                    type=argparse.FileType('r'),
                    help='Pipeline-template yml file')
PARSER.add_argument("-v", "--pipeline-variables",
                    required=True,
                    type=argparse.FileType('r'),
                    help='Pipeline-variables yml file')
PARSER.add_argument("-o", "--organization",
                    required=True,
                    type=str,
                    help='Organization name')
PARSER.add_argument("-P", "--project",
                    required=True,
                    type=str,
                    help='Project_name')
PARSER.add_argument("-E", "--env",
                    required=True,
                    type=str,
                    help='Environment_name')
PARSER.add_argument("-a", "--api-url",
                    type=str,
                    help='Cycloid api url name',
                    default='https://http-api.cycloid.io')
PARSER.add_argument("--version", action='store_true',
                    help='Print script version')
ARGS = PARSER.parse_args()


def login(apilogin, api_password, api_url, organization, insecure=False):
    payload = {'email': apilogin, 'password': api_password}
    headers = {'content-type': 'application/vnd.cycloid.io.v1+json'}

    verify=True
    if insecure:
        verify=False
    r = None
    try:
        # Get user token
        r = requests.post('%s/user/login' % (api_url), data=json.dumps(payload), headers=headers, verify=verify)
        user_token = r.json().get('data').get('token')
        # Get org token
        headers['Authorization'] = 'Bearer %s' % user_token
        r = requests.get('%s/user/refresh_token?organization_canonical=%s' % (api_url, organization), headers=headers, verify=verify)
        return r.json().get('data').get('token')
    except Exception as e:
        if r is not None:
            err = r.text
        else:
            err = e
        log.error("There is an error on login, please check your configuration - %s" % err)
        exit(1)


def update_pipeline(api_url, token, organization, project, env, pipeline_template, pipeline_variables):
    pipeline_name = "%s-%s" % (project, env)
    try:
        y_pipe=yaml.safe_load(pipeline_template)
        y_vars=yaml.safe_load(pipeline_variables)
    except yaml.YAMLError as exc:
        print(exc)

    data = {
        "passed_config": json.dumps(y_pipe),
        "yaml_vars": json.dumps(y_vars)
    }
    headers = {
        'content-type': 'application/vnd.cycloid.io.v1+json',
        'Authorization':'Bearer %s' % token
    }

    r = requests.put('%s/organizations/%s/projects/%s/pipelines/%s' % (api_url, organization, project, pipeline_name),

                     data=json.dumps(data), headers=headers)
    log.debug(r.text)
    if r.status_code != 200:
        log.error("Unable pipeline : %s" % r.text)
        exit(1)


if __name__ == "__main__":

    if ARGS.version:
        print("version: %s" % (VERSION))
        sys.exit(0)

    token = login(ARGS.username, ARGS.password, ARGS.api_url, ARGS.organization, ARGS.insecure)
    update_pipeline(api_url=ARGS.api_url,
                    token=token,
                    organization=ARGS.organization,
                    project=ARGS.project,
                    env=ARGS.env,
                    pipeline_template=ARGS.pipeline_template,
                    pipeline_variables=ARGS.pipeline_variables)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131