package main

import (
	"flag"
	"fmt"
	"os"

	"github.com/Azure/azure-sdk-for-go/arm/servicebus"

	"github.com/Azure/go-autorest/autorest"
	"github.com/Azure/go-autorest/autorest/adal"
	"github.com/Azure/go-autorest/autorest/azure"
)

//AzureCredentials represents the account information needed to authenticate on Azure
type AzureCredentials struct {
	TenantID       string
	ClientID       string
	ClientSecret   string
	SubscriptionID string
}

var azureCredentialsConfig AzureCredentials
var azureResourceGroup, azureNamespace string

func init() {
	azureCredentialsConfig = AzureCredentials{
		TenantID:       os.Getenv("AZURE_TENANT_ID"),
		ClientID:       os.Getenv("AZURE_CLIENT_ID"),
		ClientSecret:   os.Getenv("AZURE_CLIENT_SECRET"),
		SubscriptionID: os.Getenv("AZURE_SUBSCRIPTION_ID"),
	}

	//Command line args override the environment variables
	flag.StringVar(&azureCredentialsConfig.ClientID, "clientID", "", "Define this client ID in azure Active Directory")
	flag.StringVar(&azureCredentialsConfig.ClientSecret, "clientSecret", "", "Define this client Secret in azure Active Directory")
	flag.StringVar(&azureCredentialsConfig.TenantID, "tenantID", "", "Define this client tenant ID in azure Active Directory")
	flag.StringVar(&azureCredentialsConfig.SubscriptionID, "subscriptionID", "", "Define account subscription in azure")
	flag.StringVar(&azureResourceGroup, "resourceGroup", "", "Define the resource group in azure")
	flag.StringVar(&azureNamespace, "namespace", "", "Define the namespace in azure")
}

func main() {
	flag.Parse()

	oauthConfig, err := adal.NewOAuthConfig(azure.PublicCloud.ActiveDirectoryEndpoint, azureCredentialsConfig.TenantID)
	onErrorFail(err, "OAuthConfigForTenant failed")

	spToken, err := adal.NewServicePrincipalToken(*oauthConfig, azureCredentialsConfig.ClientID, azureCredentialsConfig.ClientSecret, azure.PublicCloud.ResourceManagerEndpoint)
	onErrorFail(err, "NewServicePrincipalToken failed")

	client := servicebus.NewTopicsClient(azureCredentialsConfig.SubscriptionID)
	client.Authorizer = autorest.NewBearerAuthorizer(spToken)

	fmt.Printf("Listing all topics on: %s - %s\n", azureResourceGroup, azureNamespace)

	topics, err := client.ListAll(azureResourceGroup, azureNamespace)
	onErrorFail(err, "Fail to get bus topics")

	for _, topic := range *topics.Value {
		fmt.Printf("%s\n", *topic.Name)
	}
}

func onErrorFail(err error, message string) {
	if err != nil {
		fmt.Printf("%s: %s\n", message, err)
		os.Exit(1)
	}
}

func getEnvVarOrExit(varName string) string {
	value := os.Getenv(varName)
	if value == "" {
		fmt.Printf("Missing environment variable %s\n", varName)
		os.Exit(1)
	}
	return value
}