#!/usr/bin/env node const execSync = require("child_process").execSync; const { writeFileSync } = require("fs"); const { write } = require("node:fs"); const { parseArgs } = require("node:util"); const args = parseArgs({ options: { "app-name": { type: "string", short: "a" }, help: { type: "boolean", short: "h" }, }, }); const config = {}; if (args.values["app-name"]) { config.appName = args.values["app-name"]; } else { config.appName = "Azure Node Playground"; } // Get the tenant ID try { config.tenantId = execSync(`az account show --query "tenantId" -o tsv`) .toString() .trim(); } catch (error) { console.error("Failed to get Azure tenant ID."); process.exit(1); } if (config.tenantId) { console.log(`Using Tenant ID: ${config.tenantId}`); } else { console.error("Failed to get Azure tenant ID."); process.exit(1); } try { const appIdList = JSON.parse( execSync( `az ad app list --filter "displayName eq '${config.appName}'" -o json`, ) .toString() .trim(), ); if (appIdList.length !== 1) { throw new Error("App not found or multiple apps with the same name."); } config.appId = appIdList[0].appId; } catch (error) { console.error("Failed to query Azure AD applications."); process.exit(1); } if (config.appId) { console.log(`App already exists with ID: ${config.appId}`); } else { // Create the Azure AD application, capturing the JSON output, and extracting the .appId try { config.appId = execSync( `az ad app create --display-name "${config.appName}" --query "appId" -o tsv`, ) .toString() .trim(); } catch (error) { console.error("Failed to create Azure AD application."); process.exit(1); } console.log(`Created App with ID: ${config.appId}`); } // Chech if service principal exists let spObjId; try { const spIdList = JSON.parse( execSync(`az ad sp list --filter "appId eq '${config.appId}'" -o json`) .toString() .trim(), ); if (spIdList.length === 1) { spObjId = spIdList[0].objectId; } else { spObjId = null; } } catch (error) { console.error("Failed to query service principals."); process.exit(1); } if (spObjId) { console.log("Using existing service principal."); } else { // Now create the service principal for the app try { spObjId = execSync(`az ad sp create --id ${config.appId}`); console.log("Service principal created."); } catch (error) { console.log("Failed to create service principal."); } } // Write the APP_ID to the .env file const envContent = `AZ_APP_NAME="${config.appName}" ARM_CLIENT_ID=${config.appId} ARM_TENANT_ID=${config.tenantId} `; writeFileSync(".env", envContent); console.log(".env file created with AZ_APP_NAME, ARM_CLIENT_ID, and ARM_TENANT_ID."); // Save the config to the 'config.js' file. writeFileSync( "config.js", `export const config = ${JSON.stringify(config, null, 4)};\n`, ); console.log("config.js file created."); console.log("Setup complete.");