#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# PowerShell Remoting Protocol Client

# Copyright (C) 2019 Checkmk GmbH - License: GNU General Public License v2
# This file is part of Checkmk (https://checkmk.com). It is subject to the terms and
# conditions defined in the file COPYING, which is part of this source code package.

import os
import sys

try:
    from pypsrp.client import Client
except:
    print("Python module " "pypsrp" " not available. Please install with: pip3 install pypsrp")
    sys.exit(2)

import cmk.utils.password_store


def from_environment(env):
    user = os.environ.get("PARAMETER_RUNAS")
    password = os.environ.get("PARAMETER_PASSWORD")
    command = os.environ.get("PARAMETER_COMMAND")
    address = os.environ.get("ALERT_HOSTADDRESS")

    if not user or not command or not password:
        sys.stdout.write("Need user, password and command as arguments\n")
        sys.exit(3)

    if not address:
        sys.stdout.write("Environment ALERT_HOSTADDRESS is missing\n")
        sys.exit(3)

    return user, password, command, address


def main(argv=None):
    if argv is None:
        argv = sys.argv

    user, password, command, address = from_environment(os.environ)

    if password.startswith("store\t"):
        password_id = password.split("\t", 1)[1]
        try:
            password = cmk.password_store.load().get(password_id)
        except KeyError:
            raise Exception("pwstore: Password '%s' does not exist" % password_id)
    elif password.startswith("password\t"):
        password = password.split("\t", 1)[1]

    client = Client(address, username=user, password=password, cert_validation=False)
    stdout, stderr, rc = client.execute_cmd(command)

    return rc


if __name__ == "__main__":
    sys.exit(main())
