#!/bin/bash

# Define variables
PREFIX="$(head /dev/urandom | tr -dc 'a-z0-9' | head -c 4)"
LOCATION="westeurope"
RESOURCE_GROUP_NAME="${PREFIX}-rg"
FUNCTION_APP_NAME="${PREFIX}-func"
STORAGE_ACCOUNT_NAME="${PREFIX}storage"
STORAGE_ACCOUNT_SKU="Standard_LRS"
RUNTIME="java"
RUNTIME_VERSION="21.0"


# Create resource group
echo "Creating resource group $RESOURCE_GROUP_NAME in location $LOCATION..."
az group create \
    --name "$RESOURCE_GROUP_NAME" \
    --location "$LOCATION"

# Create storage account
echo "Creating storage account: $STORAGE_ACCOUNT_NAME"
az storage account create \
    --resource-group "$RESOURCE_GROUP_NAME" \
    --name "$STORAGE_ACCOUNT_NAME" \
    --location "$LOCATION" \
    --sku "$STORAGE_ACCOUNT_SKU"

# Get storage account primary key
echo "Getting storage account key for $STORAGE_ACCOUNT_NAME..."
STORAGE_ACCOUNT_KEY=$(az storage account keys list \
    --account-name "$STORAGE_ACCOUNT_NAME" \
    --resource-group "$RESOURCE_GROUP_NAME" \
    --query "[0].value" \
    --output tsv)

# Create the function app
echo "Creating function app: $FUNCTION_APP_NAME..."
az functionapp create \
    --resource-group "$RESOURCE_GROUP_NAME" \
    --consumption-plan-location "$LOCATION" \
    --runtime "$RUNTIME" \
    --runtime-version "$RUNTIME_VERSION" \
    --functions-version 4 \
    --name "$FUNCTION_APP_NAME" \
    --os-type "linux" \
    --storage-account "$STORAGE_ACCOUNT_NAME"

# Set function app settings
echo "Configuring app settings for Function App: $FUNCTION_APP_NAME..."
STORAGE_CONNECTION_STRING="DefaultEndpointsProtocol=https;AccountName=$STORAGE_ACCOUNT_NAME;AccountKey=$STORAGE_ACCOUNT_KEY;EndpointSuffix=core.windows.net"
az functionapp config appsettings set \
    --name "$FUNCTION_APP_NAME" \
    --resource-group "$RESOURCE_GROUP_NAME" \
    --settings \
    AzureWebJobsStorage="$STORAGE_CONNECTION_STRING" \
    STORAGE_ACCOUNT_CONNECTION_STRING="$STORAGE_CONNECTION_STRING" \
    WEBSITE_CONTENTAZUREFILECONNECTIONSTRING="$STORAGE_CONNECTION_STRING"

# Checkout Project
mvn archetype:generate -B -DarchetypeGroupId=com.microsoft.azure -DarchetypeArtifactId=azure-functions-archetype -DgroupId=com.company -DartifactId=project -Dversion=1.0-SNAPSHOT -Dpackage=com.company.project

# Build the project
cd project && mvn clean package && cd ..

# Deploy the function app code
echo "Deploying function app code to Function App: $FUNCTION_APP_NAME..."
az functionapp deploy \
    --resource-group "$RESOURCE_GROUP_NAME" \
    --name "$FUNCTION_APP_NAME" \
    --src-path "project/target/project-1.0-SNAPSHOT.jar" \
    --type jar --debug

echo "Deleting test project.."
rm -r project

echo "Deleting Resource Group..."
az group delete --name "$RESOURCE_GROUP_NAME" --yes
