resource "scaleway_iam_application" "backup_app" {
  name = "k8s_backup_app"
}

resource "scaleway_iam_application" "mail_app" {
  name = "mail_app"
}

resource "scaleway_iam_application" "nextcloud_app" {
  name = "nextcloud_app"
}

resource "scaleway_iam_application" "dovecot_app" {
  name = "dovecot_app"
}

resource "scaleway_iam_policy" "object_read_write_backup" {
  name           = "K8s backup app policy"
  description    = "Gives k8s backup job access to object storage in project"
  application_id = scaleway_iam_application.backup_app.id

  rule {
    project_ids = [data.scaleway_account_project.default.id]
    permission_set_names = [
      "ObjectStorageObjectsWrite",
      "ObjectStorageObjectsRead",
      "ObjectStorageObjectsDelete",
      "ObjectStorageBucketsRead"
    ]
  }
}

resource "scaleway_iam_policy" "email_full_access" {
  name           = "Email full access policy"
  description    = "Gives access to transactional email in project"
  application_id = scaleway_iam_application.mail_app.id

  rule {
    project_ids = [data.scaleway_account_project.default.id]
    permission_set_names = [
      "TransactionalEmailFullAccess",
    ]
  }
}

resource "scaleway_iam_policy" "object_read_write_nextcloud" {
  name           = "Nextcloud app policy"
  description    = "Gives nextcloud job access to object storage in project"
  application_id = scaleway_iam_application.nextcloud_app.id

  rule {
    project_ids = [data.scaleway_account_project.default.id]
    permission_set_names = [
      "ObjectStorageObjectsWrite",
      "ObjectStorageObjectsRead",
      "ObjectStorageBucketsRead",
      "ObjectStorageBucketsWrite",
      "ObjectStorageObjectsDelete"
    ]
  }
}

resource "scaleway_iam_policy" "object_read_write_dovecot" {
  name           = "Dovecot app policy"
  description    = "Gives dovecot job access to object storage in project"
  application_id = scaleway_iam_application.dovecot_app.id

  rule {
    project_ids = [data.scaleway_account_project.default.id]
    permission_set_names = [
      "ObjectStorageObjectsWrite",
      "ObjectStorageObjectsRead",
      "ObjectStorageBucketsRead",
      "ObjectStorageBucketsWrite",
      "ObjectStorageObjectsDelete"
    ]
  }
}

resource "scaleway_iam_api_key" "backup_app_api" {
  application_id = scaleway_iam_application.backup_app.id
  description    = "k8s backup app API key"
}

resource "scaleway_iam_api_key" "mail_app_api" {
  application_id = scaleway_iam_application.mail_app.id
  description    = "mail access API key"
}

resource "scaleway_iam_api_key" "nextcloud_app_api" {
  application_id = scaleway_iam_application.nextcloud_app.id
  description    = "nextcloud access API key"
}

resource "scaleway_iam_api_key" "dovecot_app_api" {
  application_id = scaleway_iam_application.dovecot_app.id
  description    = "dovecot access API key"
}
