{
  "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "logicAppName": {
      "type": "string",
      "defaultValue": "Lab539-AiTM-Feed-Client",
      "metadata": {
        "description": "Name of the Logic App"
      }
    },
    "location": {
      "type": "string",
      "defaultValue": "[resourceGroup().location]"
    },
    "ConfigurationID": {
      "type": "string",
      "metadata": {
        "description": "Lab539 Configuration ID"
      }
    },
    "ApiKey": {
      "type": "securestring",
      "metadata": {
        "description": "Lab539 API Key"
      }
    },
    "TenantID": {
      "type": "string",
      "metadata": {
        "description": "Azure AD Tenant ID"
      }
    },
    "AppID": {
      "type": "string",
      "metadata": {
        "description": "Service Principal Application ID"
      }
    },
    "Secret": {
      "type": "securestring",
      "metadata": {
        "description": "Service Principal Secret"
      }
    },
    "DelayBetweenUpdates": {
      "type": "int",
      "defaultValue": 10,
      "metadata": {
        "description": "Delay in seconds between processing each feed"
      }
    },
    "EnableErrorReporting": {
      "type": "bool",
      "defaultValue": false,
      "metadata": {
        "description": "Enable error reporting to Lab539"
      }
    }
  },
  "resources": [
    {
      "type": "Microsoft.Logic/workflows",
      "apiVersion": "2019-05-01",
      "name": "[parameters('logicAppName')]",
      "location": "[parameters('location')]",
      "properties": {
        "state": "Enabled",
        "definition": {
          "$schema": "https://schema.management.azure.com/providers/Microsoft.Logic/schemas/2016-06-01/workflowdefinition.json#",
          "contentVersion": "1.0.0.0",
          "triggers": {
            "Recurrence": {
              "recurrence": {
                "interval": 17,
                "frequency": "Minute"
              },
              "evaluatedRecurrence": {
                "interval": 17,
                "frequency": "Minute"
              },
              "type": "Recurrence"
            }
          },
          "actions": {
            "Get_enabled_feeds": {
              "runAfter": {},
              "type": "Http",
              "inputs": {
                "uri": "https://aitm.lab539.io/v1.0/account/get-named-location-status/@{parameters('ConfigurationID')}",
                "method": "GET",
                "headers": {
                  "Authorization": "Bearer @{parameters('ApiKey')}"
                }
              }
            },
            "Parse_feed_status": {
              "runAfter": {
                "Get_enabled_feeds": [
                  "Succeeded"
                ]
              },
              "type": "ParseJson",
              "inputs": {
                "content": "@body('Get_enabled_feeds')",
                "schema": {
                  "type": "array",
                  "items": {
                    "type": "object",
                    "properties": {
                      "type": {
                        "type": "string"
                      },
                      "displayName": {
                        "type": "string"
                      },
                      "enabled": {
                        "type": "boolean"
                      },
                      "namedLocationId": {
                        "type": [
                          "string",
                          "null"
                        ]
                      }
                    }
                  }
                }
              }
            },
            "Filter_enabled_feeds": {
              "runAfter": {
                "Parse_feed_status": [
                  "Succeeded"
                ]
              },
              "type": "Query",
              "inputs": {
                "from": "@body('Parse_feed_status')",
                "where": "@equals(item()['enabled'], true)"
              }
            },
            "For_each_enabled_feed": {
              "foreach": "@body('Filter_enabled_feeds')",
              "actions": {
                "Get_feed_data": {
                  "runAfter": {},
                  "type": "Http",
                  "inputs": {
                    "uri": "https://aitm.lab539.io/v1.0/named-location/@{items('For_each_enabled_feed')['type']}",
                    "method": "GET",
                    "headers": {
                      "Authorization": "Bearer @{parameters('ApiKey')}"
                    }
                  }
                },
                "Parse_feed_data": {
                  "runAfter": {
                    "Get_feed_data": [
                      "Succeeded"
                    ]
                  },
                  "type": "ParseJson",
                  "inputs": {
                    "content": "@body('Get_feed_data')",
                    "schema": {
                      "type": "object",
                      "properties": {}
                    }
                  }
                },
                "Check_if_has_location_id": {
                  "runAfter": {
                    "Parse_feed_data": [
                      "Succeeded"
                    ]
                  },
                  "type": "If",
                  "expression": {
                    "and": [
                      {
                        "not": {
                          "equals": [
                            "@items('For_each_enabled_feed')?['namedLocationId']",
                            "@null"
                          ]
                        }
                      },
                      {
                        "not": {
                          "equals": [
                            "@items('For_each_enabled_feed')?['namedLocationId']",
                            ""
                          ]
                        }
                      }
                    ]
                  },
                  "actions": {
                    "Update_existing_location": {
                      "runAfter": {},
                      "type": "Http",
                      "inputs": {
                        "uri": "https://graph.microsoft.com/v1.0/identity/conditionalAccess/namedLocations/@{items('For_each_enabled_feed')['namedLocationId']}",
                        "method": "PATCH",
                        "headers": {
                          "Content-Type": "application/json"
                        },
                        "body": "@body('Parse_feed_data')",
                        "authentication": {
                          "type": "ActiveDirectoryOAuth",
                          "authority": "",
                          "tenant": "@{parameters('TenantID')}",
                          "audience": "https://graph.microsoft.com/",
                          "clientId": "@{parameters('AppID')}",
                          "secret": "@{parameters('Secret')}"
                        }
                      }
                    },
                    "Check_update_success": {
                      "runAfter": {
                        "Update_existing_location": [
                          "Succeeded","Failed"
                        ]
                      },
                      "type": "If",
                      "expression": {
                        "and": [
                          {
                            "equals": [
                              "@outputs('Update_existing_location')?['statusCode']",
                              204
                            ]
                          }
                        ]
                      },
                      "actions": {},
                      "else": {
                        "actions": {
                          "Report_update_error": {
                            "runAfter": {},
                            "type": "If",
                            "expression": {
                              "and": [
                                {
                                  "equals": [
                                    "@parameters('EnableErrorReporting')",
                                    true
                                  ]
                                }
                              ]
                            },
                            "actions": {
                              "Send_update_error": {
                                "runAfter": {},
                                "type": "Http",
                                "inputs": {
                                  "uri": "https://aitm.lab539.io/v1.0/account/error",
                                  "method": "POST",
                                  "headers": {
                                    "Authorization": "Bearer @{parameters('ApiKey')}",
                                    "Content-Type": "application/json"
                                  },
                                  "body": {
                                    "timestamp": "@{utcNow()}",
                                    "feedType": "@{items('For_each_enabled_feed')['type']}",
                                    "operation": "update",
                                    "statusCode": "@outputs('Update_existing_location')['statusCode']",
                                    "errorMessage": "@{body('Update_existing_location')}",
                                    "namedLocationId": "@{items('For_each_enabled_feed')['namedLocationId']}",
                                    "configurationId": "@{parameters('ConfigurationID')}"
                                  }
                                }
                              }
                            }
                          }
                        }
                      }
                    }
                  },
                  "else": {
                    "actions": {
                      "Create_minimal_location": {
                        "runAfter": {},
                        "type": "Http",
                        "inputs": {
                          "uri": "https://graph.microsoft.com/v1.0/identity/conditionalAccess/namedLocations",
                          "method": "POST",
                          "headers": {
                            "Content-Type": "application/json"
                          },
                          "body": {
                            "@@odata.type": "#microsoft.graph.ipNamedLocation",
                            "displayName": "@{items('For_each_enabled_feed')['displayName']}",
                            "isTrusted": false,
                            "ipRanges": [
                              {
                                "@@odata.type": "#microsoft.graph.iPv4CidrRange",
                                "cidrAddress": "54.242.109.54/32"
                              }
                            ]
                          },
                          "authentication": {
                            "type": "ActiveDirectoryOAuth",
                            "authority": "",
                            "tenant": "@{parameters('TenantID')}",
                            "audience": "https://graph.microsoft.com/",
                            "clientId": "@{parameters('AppID')}",
                            "secret": "@{parameters('Secret')}"
                          }
                        }
                      },
                      "Parse_created_location": {
                        "runAfter": {
                          "Create_minimal_location": [
                            "Succeeded"
                          ]
                        },
                        "type": "ParseJson",
                        "inputs": {
                          "content": "@body('Create_minimal_location')",
                          "schema": {
                            "type": "object",
                            "properties": {
                              "id": {
                                "type": "string"
                              }
                            }
                          }
                        }
                      },
                      "Store_new_location_id": {
                        "runAfter": {
                          "Parse_created_location": [
                            "Succeeded"
                          ]
                        },
                        "type": "Http",
                        "inputs": {
                          "uri": "https://aitm.lab539.io/v1.0/account/set-named-location-id/@{parameters('ConfigurationID')}/@{items('For_each_enabled_feed')['type']}/@{body('Parse_created_location')['id']}",
                          "method": "POST",
                          "headers": {
                            "Authorization": "Bearer @{parameters('ApiKey')}",
                            "Content-Type": "application/json"
                          }
                        }
                      },
                      "Delay_before_populate": {
                        "runAfter": {
                          "Store_new_location_id": [
                            "Succeeded",
                            "Failed"
                          ]
                        },
                        "type": "Wait",
                        "inputs": {
                          "interval": {
                            "count": 10,
                            "unit": "Second"
                          }
                        }
                      },
                      "Populate_with_full_data": {
                        "runAfter": {
                          "Delay_before_populate": [
                            "Succeeded"
                          ]
                        },
                        "type": "Http",
                        "inputs": {
                          "uri": "https://graph.microsoft.com/v1.0/identity/conditionalAccess/namedLocations/@{body('Parse_created_location')['id']}",
                          "method": "PATCH",
                          "headers": {
                            "Content-Type": "application/json"
                          },
                          "body": "@body('Parse_feed_data')",
                          "authentication": {
                            "type": "ActiveDirectoryOAuth",
                            "authority": "",
                            "tenant": "@{parameters('TenantID')}",
                            "audience": "https://graph.microsoft.com/",
                            "clientId": "@{parameters('AppID')}",
                            "secret": "@{parameters('Secret')}"
                          }
                        }
                      },
                      "Check_populate_success": {
                        "runAfter": {
                          "Populate_with_full_data": [
                            "Succeeded","Failed"
                          ]
                        },
                        "type": "If",
                        "expression": {
                          "and": [
                            {
                              "equals": [
                                "@outputs('Populate_with_full_data')?['statusCode']",
                                204
                              ]
                            }
                          ]
                        },
                        "actions": {},
                        "else": {
                          "actions": {
                            "Report_create_error": {
                              "runAfter": {},
                              "type": "If",
                              "expression": {
                                "and": [
                                  {
                                    "equals": [
                                      "@parameters('EnableErrorReporting')",
                                      true
                                    ]
                                  }
                                ]
                              },
                              "actions": {
                                "Send_create_error": {
                                  "runAfter": {},
                                  "type": "Http",
                                  "inputs": {
                                    "uri": "https://aitm.lab539.io/v1.0/account/error",
                                    "method": "POST",
                                    "headers": {
                                      "Authorization": "Bearer @{parameters('ApiKey')}",
                                      "Content-Type": "application/json"
                                    },
                                    "body": {
                                      "timestamp": "@{utcNow()}",
                                      "feedType": "@{items('For_each_enabled_feed')['type']}",
                                      "operation": "create_populate",
                                      "statusCode": "@outputs('Populate_with_full_data')['statusCode']",
                                      "errorMessage": "@{body('Populate_with_full_data')}",
                                      "namedLocationId": "@{body('Parse_created_location')['id']}",
                                      "configurationId": "@{parameters('ConfigurationID')}"
                                    }
                                  }
                                }
                              }
                            }
                          }
                        }
                      }
                    }
                  }
                },
                "Delay_between_feeds": {
                  "runAfter": {
                    "Check_if_has_location_id": [
                      "Succeeded",
                      "Failed"
                    ]
                  },
                  "type": "Wait",
                  "inputs": {
                    "interval": {
                      "count": "@parameters('DelayBetweenUpdates')",
                      "unit": "Second"
                    }
                  }
                }
              },
              "runAfter": {
                "Filter_enabled_feeds": [
                  "Succeeded"
                ]
              },
              "type": "Foreach",
              "runtimeConfiguration": {
                "concurrency": {
                  "repetitions": 1
                }
              }
            }
          },
          "outputs": {},
          "parameters": {
            "ConfigurationID": {
              "type": "String"
            },
            "TenantID": {
              "type": "String"
            },
            "AppID": {
              "type": "String"
            },
            "Secret": {
              "type": "SecureString"
            },
            "ApiKey": {
              "type": "SecureString"
            },
            "DelayBetweenUpdates": {
              "type": "Int"
            },
            "EnableErrorReporting": {
              "type": "Bool"
            }
          }
        },
        "parameters": {
          "ConfigurationID": {
            "value": "[parameters('ConfigurationID')]"
          },
          "TenantID": {
            "value": "[parameters('TenantID')]"
          },
          "AppID": {
            "value": "[parameters('AppID')]"
          },
          "Secret": {
            "value": "[parameters('Secret')]"
          },
          "ApiKey": {
            "value": "[parameters('ApiKey')]"
          },
          "DelayBetweenUpdates": {
            "value": "[parameters('DelayBetweenUpdates')]"
          },
          "EnableErrorReporting": {
            "value": "[parameters('EnableErrorReporting')]"
          }
        }
      }
    }
  ]
}