#!/bin/bash

# Copyright 2018 Pax Automa Systems, Inc.
#
# 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.

CONTROLLER_IP=${CONTROLLER_IP:-192.168.33.10}

get_credentials() {
    mkdir -p keys
    cd keys

    local url="http://${CONTROLLER_IP}/api/v1/clientcert"

    echo -n "Username: "
    read username
    echo -n "Password: "
    read -s password
    echo

    echo Downloading ${url}
    if ! curl --fail -L --user "${username//:/%3A}:${password//:/%3A}" ${url} | tar -xz; then
        echo Failed to download credentials >&2
        exit 1
    fi
}

if [ ! -d keys/operos-credentials ]; then
    echo "Credentials not found. Please log in to download from Operos controller."
    (get_credentials)
fi

kubectl --kubeconfig=keys/operos-credentials/kubeconfig $@
