module "default_tags" {
  source             = "git@github.com:theorchard/terraform-default-tags.git//?ref=2.0.0"
  environment        = var.environment
  application_family = var.application_family
  service_name       = var.service_name
  team_name          = var.team_name
}

provider "aws" {
  region = var.region

  default_tags {
    tags = module.default_tags.tags
  }
}

provider "aws" {
  region  = var.region
  alias   = "networking"
  profile = "networking"

  default_tags {
    tags = module.default_tags.tags
  }
}

# Caller Identity
data "aws_caller_identity" "current" {}

module "vpc_info" {
  source      = "git@github.com:theorchard/terraform-vpc-info.git//?ref=3.1.0"

  environment = var.environment
}

# Terraform backends
terraform {
  backend "s3" {
    bucket  = "orcd-terraform-state"
    key     = "qa/daemon-video/terraform.tfstate"
    region  = "us-east-1"
    encrypt = true
  }
}

data "aws_iam_policy_document" "assume_statemachines_role" {
  statement {
    actions = ["sts:AssumeRole"]

    principals {
      type        = "Service"
      identifiers = ["states.amazonaws.com"]
    }
  }
}

data "aws_iam_policy_document" "daemon_video_stepfunctions_policy_document" {
  statement {
    effect = "Allow"

    actions = [
      "states:GetActivityTask",
    ]

    resources = [
      "arn:aws:states:${var.region}:${data.aws_caller_identity.current.account_id}:activity:${var.environment}_daemon_video_*",
    ]
  }

  statement {
    effect = "Allow"

    actions = [
      "states:SendTaskHeartbeat",
      "states:SendTaskSuccess",
      "states:SendTaskFailure",
    ]

    resources = [
      "*",
    ]
  }
}

locals {
  iam_user_managed_policies = [
    "arn:aws:iam::aws:policy/AmazonEC2ContainerRegistryReadOnly",
    "arn:aws:iam::aws:policy/CloudWatchFullAccess",
    module.daemon_video_service_owsrequest.policy_arn_output,
    aws_iam_policy.s3_raw_dir_putonly_policy.arn,
    aws_iam_policy.daemon_video_stepfunctions_policy.arn,
    module.video_on_prem_sqs.sqs_minimal_policy_arn_output,
    data.aws_iam_policy.s3_mezzanine_dir_readonly_policy.arn,
  ]
}

resource "aws_iam_policy" "daemon_video_stepfunctions_policy" {
  name   = "${var.environment}-stepfunctions-daemon-video-stepfunctions-policy"
  policy = data.aws_iam_policy_document.daemon_video_stepfunctions_policy_document.json
}

resource "aws_sfn_activity" "daemon_video_start_workflow" {
  name = "${var.environment}_daemon_video_start_workflow"
}

resource "aws_sfn_activity" "daemon_video_extract_metadata" {
  name = "${var.environment}_daemon_video_extract_metadata"
}

resource "aws_sfn_activity" "daemon_video_detect_black_intervals_at_beginning_and_end_of_video" {
  name = "${var.environment}_daemon_video_detect_black_intervals_at_beginning_and_end_of_video"
}

resource "aws_sfn_activity" "daemon_video_detect_silent_intervals_at_beginning_and_end_of_audio" {
  name = "${var.environment}_daemon_video_detect_silent_intervals_at_beginning_and_end_of_audio"
}

resource "aws_sfn_activity" "daemon_video_detect_video_location_and_dimensions_within_black_border" {
  name = "${var.environment}_daemon_video_detect_video_location_and_dimensions_within_black_border"
}

resource "aws_sfn_activity" "daemon_video_detect_max_volume" {
  name = "${var.environment}_daemon_video_detect_max_volume"
}

resource "aws_sfn_activity" "daemon_video_calculate_audio_stats" {
  name = "${var.environment}_daemon_video_calculate_audio_stats"
}

resource "aws_sfn_activity" "daemon_video_transfer_from_browser_to_s3" {
  name = "${var.environment}_daemon_video_transfer_from_browser_to_s3"
}

resource "aws_sfn_activity" "daemon_video_is_transfer_from_browser_to_s3_done" {
  name = "${var.environment}_daemon_video_is_transfer_from_browser_to_s3_done"
}

resource "aws_sfn_activity" "daemon_video_log_transfer_completed" {
  name = "${var.environment}_daemon_video_log_transfer_completed"
}

resource "aws_sfn_activity" "daemon_video_log_transfer_timed_out" {
  name = "${var.environment}_daemon_video_log_transfer_timed_out"
}

resource "aws_sfn_activity" "daemon_video_transfer_from_s3_to_s3" {
  name = "${var.environment}_daemon_video_transfer_from_s3_to_s3"
}

resource "aws_sfn_activity" "daemon_video_transfer_from_google_drive_to_s3" {
  name = "${var.environment}_daemon_video_transfer_from_google_drive_to_s3"
}

resource "aws_sfn_activity" "daemon_video_transfer_from_dropbox_to_s3" {
  name = "${var.environment}_daemon_video_transfer_from_dropbox_to_s3"
}

resource "aws_sfn_activity" "daemon_video_transfer_prores_from_s3_to_ripper" {
  name = "${var.environment}_daemon_video_transfer_prores_from_s3_to_ripper"
}

resource "aws_sfn_activity" "daemon_video_is_ripper_mezzanine_processing_done" {
  name = "${var.environment}_daemon_video_is_ripper_mezzanine_processing_done"
}

resource "aws_sfn_activity" "daemon_video_transfer_h264_from_s3_to_ripper" {
  name = "${var.environment}_daemon_video_transfer_h264_from_s3_to_ripper"
}

resource "aws_sfn_activity" "daemon_video_transfer_h264_from_s3_to_ripper_storage" {
  name = "${var.environment}_daemon_video_transfer_h264_from_s3_to_ripper_storage"
}

resource "aws_sfn_activity" "daemon_video_is_ripper_h264_processing_done" {
  name = "${var.environment}_daemon_video_is_ripper_h264_processing_done"
}

resource "aws_sfn_activity" "daemon_video_validate_metadata" {
  name = "${var.environment}_daemon_video_validate_metadata"
}

resource "aws_sfn_activity" "daemon_video_extract_prores_mezzanine_metadata" {
  name = "${var.environment}_daemon_video_extract_prores_mezzanine_metadata"
}

resource "aws_sfn_activity" "daemon_video_convert_thumbnails_to_tiffs" {
  name = "${var.environment}_daemon_video_convert_thumbnails_to_tiffs"
}

resource "aws_sfn_activity" "daemon_video_write_thumbnail_locations_to_video_asset_table" {
  name = "${var.environment}_daemon_video_write_thumbnail_locations_to_video_asset_table"
}

resource "aws_sfn_activity" "daemon_video_write_mezz_video_locations_to_video_asset_table" {
  name = "${var.environment}_daemon_video_write_mezz_video_locations_to_video_asset_table"
}

resource "aws_sfn_activity" "daemon_video_validate_analysis" {
  name = "${var.environment}_daemon_video_validate_analysis"
}

resource "aws_sfn_activity" "daemon_video_create_streamable_preview_and_thumbnails" {
  name = "${var.environment}_daemon_video_create_streamable_preview_and_thumbnails"
}

resource "aws_sfn_activity" "daemon_video_is_create_streamable_preview_and_thumbnails_done" {
  name = "${var.environment}_daemon_video_is_create_streamable_preview_and_thumbnails_done"
}

resource "aws_sfn_activity" "daemon_video_get_create_mezzanines_inputs" {
  name = "${var.environment}_daemon_video_get_create_mezzanines_inputs"
}

resource "aws_sfn_activity" "daemon_video_create_mezzanines" {
  name = "${var.environment}_daemon_video_create_mezzanines"
}

resource "aws_sfn_activity" "daemon_video_is_create_mezzanines_done" {
  name = "${var.environment}_daemon_video_is_create_mezzanines_done"
}

resource "aws_sfn_activity" "daemon_video_end_workflow" {
  name = "${var.environment}_daemon_video_end_workflow"
}

resource "aws_sfn_activity" "daemon_video_get_product_metadata" {
  name = "${var.environment}_daemon_video_get_product_metadata"
}

resource "aws_sfn_activity" "daemon_video_convert_default_thumbnail_to_tiff" {
  name = "${var.environment}_daemon_video_convert_default_thumbnail_to_tiff"
}

resource "aws_sfn_activity" "daemon_video_transfer_tiff_thumbnail_from_s3_to_ripper" {
  name = "${var.environment}_daemon_video_transfer_tiff_thumbnail_from_s3_to_ripper"
}

resource "aws_sfn_activity" "daemon_video_is_ripper_tiff_thumbnail_processing_done" {
  name = "${var.environment}_daemon_video_is_ripper_tiff_thumbnail_processing_done"
}

resource "aws_sfn_activity" "daemon_video_mark_video_product_as_approved" {
  name = "${var.environment}_daemon_video_mark_video_product_as_approved"
}

module "daemon_video_fargate_environment" {
  source = "git@github.com:theorchard/terraform-fargate.git//?ref=5.8.1"

  providers = {
    aws.dns = aws.networking
  }

  application_family                    = var.application_family
  environment                           = var.environment
  service_name                          = var.service_name
  aws_region                            = var.region
  commit_sha                            = "latest"
  task_type                             = "worker"
  container_port                        = "8080"
  desired_task_count                    = 2
  minimum_capacity                      = 1
  maximum_capacity                      = 2
  task_cpu                              = 4096
  task_memory                           = 8192
  vpc_id                                = module.vpc_info.vpc_id
  fargate_service_subnets               = module.vpc_info.default_private_subnet_ids
  fargate_spot_capacity_provider_weight = 100
  task_placement_failure_alert_enabled  = true
  stopped_task_monitoring_enabled       = true

  iam_managed_policy_attachments = [
    data.aws_iam_policy.s3_thumbnails_dir_readonly_policy.arn,
    aws_iam_policy.s3_raw_dir_rw_policy.arn,
    aws_iam_policy.s3_mezzanine_dir_rw_policy.arn,
    aws_iam_policy.s3_ingest_dir_rwd_policy.arn,
    data.aws_iam_policy.s3_list_bucket_policy.arn,
    module.daemon_video_service_owsrequest.policy_arn_output,
    aws_iam_policy.daemon_video_stepfunctions_policy.arn,
    aws_iam_policy.video_mediaconvert_create_job_policy.arn,
    aws_iam_policy.video_mediaconvert_get_job_policy.arn,
    aws_iam_policy.video_mediaconvert_get_role_policy.arn,
    aws_iam_policy.video_mediaconvert_pass_role_policy.arn,
    module.video_sqs.sqs_minimal_policy_arn_output,
  ]

  environment_variables = [
    {
      Environment = var.environment
    },
    {
      LOGGER_DSN = var.LOGGER_DSN
    },
    {
      DATADOG_ENV = "${var.environment}-${var.service_name}"
    },
    {
      DD_LOGS_INJECTION = "true"
    },
    {
      SENTRY_DSN = var.DAEMON_SENTRY_DSN
    },
    {
      MEDIACONVERT_ROLE = aws_iam_role.video_mediaconvert_role.arn
    },
    {
      MEDIACONVERT_URL = var.MEDIACONVERT_URL
    },
    {
      MEDIACONVERT_QUEUE = "arn:aws:mediaconvert:${var.region}:${data.aws_caller_identity.current.account_id}:queues/Default"
    },
    {
      NUM_ACTIVITY_TASK_HANDLING_WORKERS = var.NUM_ACTIVITY_TASK_HANDLING_WORKERS
    },
    {
      MAX_TIMEOUT_BETWEEN_RESOURCE_UTILIZATION_CHECKS_SECONDS = var.MAX_TIMEOUT_BETWEEN_RESOURCE_UTILIZATION_CHECKS_SECONDS
    },
    {
      CUSTOM_METRIC_CPU_USAGE_PERCENT = var.CUSTOM_METRIC_CPU_USAGE_PERCENT
    },
    {
      CUSTOM_METRIC_MEMORY_USAGE_PERCENT = var.CUSTOM_METRIC_MEMORY_USAGE_PERCENT
    },
    {
      MAX_ALLOWED_CPU_USAGE_PERCENT = var.MAX_ALLOWED_CPU_USAGE_PERCENT
    },
    {
      MAX_ALLOWED_MEMORY_USAGE_PERCENT = var.MAX_ALLOWED_MEMORY_USAGE_PERCENT
    },
    {
      MAX_ALLOWED_MEMORY_UTILIZATION_PERCENT = var.MAX_ALLOWED_MEMORY_UTILIZATION_PERCENT
    },
    {
      MAX_TIMEOUT_BEFORE_PICKING_UP_WORK_SECONDS = var.MAX_TIMEOUT_BEFORE_PICKING_UP_WORK_SECONDS
    },
    {
      MAX_TIMEOUT_BETWEEN_PICKING_UP_WORK_AND_HANDLING_SECONDS = var.MAX_TIMEOUT_BETWEEN_PICKING_UP_WORK_AND_HANDLING_SECONDS
    },
    {
      MAX_TIMEOUT_AFTER_AWS_THROTTLING_EXCEPTION_SECONDS = var.MAX_TIMEOUT_AFTER_AWS_THROTTLING_EXCEPTION_SECONDS
    },
    {
      HEARTBEAT_PERIOD_SECONDS = var.HEARTBEAT_PERIOD_SECONDS
    },
    {
      HTTP_REQUEST_RETRY_PERIOD_SECONDS = var.HTTP_REQUEST_RETRY_PERIOD_SECONDS
    },
    {
      ACTIVITY_TASK_SQS_QUEUE_NAME = "${var.environment}-${var.daemon_video_activity_task_sqs_queue_name}"
    },
    {
      ACTIVITY_ARN_PREFIX = "arn:aws:states:us-east-1:${data.aws_caller_identity.current.account_id}:activity:"
    },
    {
      UPLOAD_FROM_BROWSER_TO_S3_TIMEOUT_THRESHOLD = var.UPLOAD_FROM_BROWSER_TO_S3_TIMEOUT_THRESHOLD
    },
  ]
}

module "fargate_service_dashboard" {
  source                            = "git@github.com:theorchard/terraform-datadog.git//modules/service//?ref=6.13.7"
  environment                       = var.environment
  service_name                      = var.service_name
  environment_type                  = "fargate"
  service_4xx_monitor_enabled       = false
  service_5xx_monitor_enabled       = false
  application_family                = var.application_family
  notification_endpoints            = "@slack-content-delivery-and-asset-mgmt-qa-alerts"
  escalation_notification_endpoints = "@slack-content-delivery-and-asset-mgmt-qa-alerts"
}
