#!/usr/bin/env bash
# @description The Commando.io command-line interface.
#
# Commando.io
# Copyright 2018 NodeSocket, LLC.
# All rights reserved.

set -eo pipefail; [[ $TRACE ]] && set -x

VERSION="1.6"

COMMAND=$1
NETRC=~/.netrc

if [ ! -z "$API_ENDPOINT" ]; then
    API_ENDPOINT=$API_ENDPOINT
else
    API_ENDPOINT="api.commando.io"
fi

function check_auth {
    if [ ! -e $NETRC ] || ! grep -Fxq "machine $API_ENDPOINT" $NETRC; then
        printf "You are not authenticated. To authenticate, run:\n\n\tcommando auth"
        exit 4
    fi
}

# First parameter (required): url
# Second parameter [optional]: Post data
function curl_request() {
    CURL_VERSION=$(curl --version | sed -n 1p)

    if [ "$2" != "" ]; then
        curl --silent --netrc --location --user-agent "Commando-Cli/$VERSION $CURL_VERSION" "https://$API_ENDPOINT/v1/$1" -X POST --data "$2"
    else
        curl --silent --netrc --location --user-agent "Commando-Cli/$VERSION $CURL_VERSION" "https://$API_ENDPOINT/v1/$1"
    fi
}

case "$COMMAND" in
    "auth")

        if [ -e $NETRC ] && grep -Fxq "machine $API_ENDPOINT" $NETRC; then
            ACCOUNT_ALIAS=$(awk '/$API_ENDPOINT/{getline; print $2}' $NETRC)
            printf "You are already authenticated. To unauthenticate, run:\n\n\tcommando unauth"
            exit 4
        fi

        read -r -p "Enter your account alias: " ACCOUNT_ALIAS
        read -r -s -p "Provide a valid API token secret key: " SECRET_KEY

        cat <<EOF >> $NETRC
machine $API_ENDPOINT
  login $ACCOUNT_ALIAS
  password $SECRET_KEY
EOF

        chmod 600 $NETRC

        ;;

    "unauth")

        check_auth

        TMP=$(mktemp ~/.netrc.XXXXXX)
        sed "/^machine $API_ENDPOINT$/{N;N;d;}" $NETRC > "$TMP"
        mv "$TMP" "$NETRC"

        ;;

    "servers")

        check_auth

        SERVER_ID=$2

        if [ "$SERVER_ID" == "" ]; then
            curl_request "servers"
        else
            curl_request "servers/$SERVER_ID"
        fi

        ;;

    "groups")

        check_auth

        GROUP_ID=$2

        if [ "$GROUP_ID" == "" ]; then
            curl_request "groups"
        else
            curl_request "groups/$GROUP_ID"
        fi

        ;;

    "recipes")

        check_auth

        RECIPE_ID=$2

        if [ "$RECIPE_ID" == "" ]; then
            curl_request "recipes"
        else
            curl_request "recipes/$RECIPE_ID"
        fi

        ;;

    "execute")

        RECIPE_ID=$2

        if [ "$RECIPE_ID" == "" ]; then
            printf "Missing required argument recipe id.\n\nUsage:\n\tcommando execute <recipe-id> (--server=<server-id> | --groups=<group-id>,<group-id>,...)"
            exit 4
        fi

        check_auth

        OPTS=$3

        # Split on equals
        SPLIT=(${OPTS//=/ })

        # If the array length is greater than 0
        if [ ${#SPLIT[@]} -gt 0 ]; then
            # --server option set
            if [ ${SPLIT[0]} == "--server" ]; then
                SERVER=${SPLIT[1]}
            # --groups option set
            elif [ ${SPLIT[0]} == "--groups" ]; then
                GROUP=${SPLIT[1]}
            fi
        fi

        if [ "$SERVER" != "" ]; then
            curl_request "recipes/$RECIPE_ID/execute" "server=$SERVER"
        elif [ "$GROUP" != "" ]; then
            curl_request "recipes/$RECIPE_ID/execute" "groups[]=$GROUP"
        else
            printf "Missing or invalid option.\n\nUsage:\n\tcommando execute <recipe-id> (--server=<server-id> | --groups=<group-id>,<group-id>,...)"
            exit 4
        fi

        ;;

    "execution-queue")

        check_auth

        EXECUTION_QUEUE_ID=$2

        if [ "$EXECUTION_QUEUE_ID" == "" ]; then
            curl_request "execution-queue"
        else
            curl_request "execution-queue/$EXECUTION_QUEUE_ID"
        fi

        ;;

    "executions")

        EXECUTION_ID=$2

        if [ "$EXECUTION_ID" == "" ]; then
            printf "Missing required argument execution id.\n\nUsage:\n\tcommando executions <execution-id>"
            exit 4
        fi

        check_auth

        curl_request "executions/$EXECUTION_ID"

        ;;

    "version" | "-v" | "--version")

        echo $VERSION

        ;;

    *)

        printf "Usage:\n\tcommando auth\n\tcommando unauth\n\tcommando servers [<server-id>]\n\tcommando groups [<group-id>]\n\tcommando recipes [<recipe-id>]\n\tcommando execute <recipe-id> (--server=<server-id> | --groups=<group-id>,<group-id>,...)\n\tcommando execution-queue [<execution-queue-id>]\n\tcommando executions <execution-id>\n\tcommando (version | --version)\n\tcommando (help | --help)"

        if [ "$COMMAND" != "help" ] && [ "$COMMAND" != "--help" ]; then
            exit 4
        fi

        ;;

esac
