#!/usr/bin/python3

import requests 
import logging as log
import sys
import os
import subprocess

log.basicConfig(level=log.INFO)


USER_ID = os.getenv('PAM_USER')
AUTH_API_PATH="/auth/cubes/"

def is_user_local():
    try:
        cat = subprocess.Popen(('cat', '/etc/passwd'), stdout=subprocess.PIPE)
        output = subprocess.check_call(('grep', '-q', USER_ID), stdin=cat.stdout)
        cat.wait()
        log.info(output)
        return True if output == 0 else False
    except subprocess.CalledProcessError as e:
        return False

def get_cube_id():
    hostname = subprocess.Popen(('hostname'), stdout=subprocess.PIPE)
    output = subprocess.check_output(('grep', '-oP', 'cube\K\d+'), stdin=hostname.stdout)
    hostname.wait()
    return output.decode("utf-8")


def get_api_url():
    cat = subprocess.Popen(('cat', '/proc/cmdline'), stdout=subprocess.PIPE)
    grep = subprocess.Popen(('grep', '-oP', 'pilab_api=\K.*($|(\s+))'), stdout=subprocess.PIPE, stdin=cat.stdout)
    output = subprocess.check_output(('tr', '-d', '\n'), stdin=grep.stdout)
    cat.wait()
    grep.wait()
    return output.decode("utf-8")


if __name__ == "__main__":
    if is_user_local():
        sys.exit(0)

    pilab_api_url = get_api_url()
    cube_id = get_cube_id()
    auth_url = pilab_api_url + AUTH_API_PATH + cube_id + '/access?username=' + USER_ID
    session = requests.Session()
    resp = session.get(auth_url)
    log.info(resp)

    if resp.status_code == 202:
        sys.exit(0)
    else:
        sys.exit(1)
