#!/usr/bin/env python3

import os
import time

import requests

CI_API_V4_URL = os.environ.get('CI_API_V4_URL')
CI_PROJECT_ID = os.environ.get('CI_PROJECT_ID')
CI_PIPELINE_ID = int(os.environ.get('CI_PIPELINE_ID'))
GITLAB_API_TOKEN = os.environ.get('GITLAB_API_TOKEN')


def get_running_pipelines():
    resp = requests.get(
        f'{CI_API_V4_URL}/projects/{CI_PROJECT_ID}/pipelines',
        {
            'scope': 'running',
        },
        headers={
            'PRIVATE-TOKEN': GITLAB_API_TOKEN,
        }
    )

    return map(lambda x: x['id'], resp.json())


if __name__ == '__main__':
    while True:
        min_pipeline_id = min(get_running_pipelines())
        if min_pipeline_id == CI_PIPELINE_ID:
            print('Current pipeline is oldest.')
            exit(0)
        else:
            print(f'Waiting {min_pipeline_id} ({CI_PIPELINE_ID})')
            time.sleep(10)
