#!/bin/bash

if [[ -z $VULTR_API_KEY ]]; then
    echo "VULTR_API_KEY environment variable not set. Exiting."
    exit 0
fi

if [[ ! -f /usr/bin/jq ]]; then
    echo "This script requires jq to be installed. Exiting."
    exit 0
fi

BIN=$(basename $0)

ENCODE() {
USER_DATA_BASE64=$(base64 -w 0 < $1)
if [ -z "$USER_DATA_BASE64" ]; then
  echo "Error: Failed to encode $1 or file is empty."
  exit 1
fi
}

INSTANCE_PAYLOAD() {
read -r -d '' INSTANCE_PAYLOAD << EOM
{
  "region": "${REGION_ID}",
  "plan": "${PLAN_ID}",
  "os_id": ${OS_ID},
  "label": "${SERVER_LABEL}",
  "hostname": "${SERVER_HOSTNAME}",
  "backups": "enabled",
  "enable_ipv6": true,
  "user_data": "${USER_DATA_BASE64}",
  "sshkey_id": ${SSH_KEY_IDS} 
}
EOM
}

SSH_PAYLOAD() {
read -r -d '' SSH_PAYLOAD << EOM
{
  "name": "${1}",
  "ssh_key": "$(cat ${2})" 
}
EOM
echo $SSH_PAYLOAD | jq
}

INSTANCE_REQUEST() {
curl -X POST "https://api.vultr.com/v2/instances" \
  -H "Authorization: Bearer ${VULTR_API_KEY}" \
  -H "Content-Type: application/json" \
  --data "${INSTANCE_PAYLOAD}" | jq
}

SSH_REQUEST() {
curl -X POST "https://api.vultr.com/v2/ssh-keys" \
  -H "Authorization: Bearer ${VULTR_API_KEY}" \
  -H "Content-Type: application/json" \
  --data "${SSH_PAYLOAD}" | jq
}

INFO_REQUEST() {
curl -X GET "https://api.vultr.com/v2/${1}" \
    -H "Authorization: Bearer ${VULTR_API_KEY}" | jq
}

case "$1" in
    regions)
        INFO_REQUEST regions
        ;;
    plans)
        INFO_REQUEST plans
        ;;
    os)
        INFO_REQUEST os
        ;;
    ssh)
        case "$2" in
            get)
                INFO_REQUEST ssh-keys
            ;;
            create)
                if [[ -n "$3" && -n "$4" ]]; then
                    SSH_PAYLOAD $3 $4
                    SSH_REQUEST
                else
                    echo "Usage $BIN $1 $2 {name} {ssh key}"
                    exit 0
                fi
            ;;
            *)
                echo "Usage $BIN $1 {get|create} {name} {ssh key}"
                exit 0
            ;;
        esac
    ;;
    deploy)
        if [[ -n "$2" && -n "$3" ]]; then
            if [ -f "$2" ] && [ -f "$3" ]; then
                source $2
                ENCODE $3
                INSTANCE_PAYLOAD
                INSTANCE_REQUEST
            fi
        else
            echo "Usage: $BIN $1 {configuration file} {userdata file}"
            exit 0
        fi
        ;;
    instances)
        INFO_REQUEST instances
        ;;
    *)
        echo "Usage: $BIN regions | plans | os | ssh | deploy | instances"
        ;;
esac
