#!/bin/bash

send_{{ service.name }}_status_hook () {
    echo -e \\nSending build status webhook...\\n

    if [ $1 -eq 0 ]; then
        cnc_build_status=${2:-"success"}
    else
        cnc_build_status="failed"
    fi

    data='{
        "token": "{{ builder.webhook_token }}",
        "status": "'"$cnc_build_status"'",
        "stage": "build",
        "service": "{{ service.name }}"
    }'
    echo "===== {{ service.name }} build status ====="
    echo "$data" | jq .
    echo "===== {{ service.name }} build status ====="

    which curl; curl_exists=$?
    if [ $curl_exists -ne 0 ]; then
        echo -e \\nWarning: Cannot find curl binary, skipping build status webhook...\\n
    else
        {% if builder.webhook_url %}
        webhook_status=$(curl -X PUT -H "Content-Type: application/json" \
        -o /dev/null \
        -d "$data" -w "%{http_code}" \
        {{ builder.webhook_url }}) || true

        if [ "$webhook_status" != "200" ]; then
            echo -e \\nBuild status webhook failed.
        else
            echo -e \\nBuild status webhook succeeded.
        fi
        {% else %}
        echo -e \\nNo webhook URL provided. Skipping build status webhook...
        {% endif %}
    fi
}

build_{{ service.name }} () {
  echo "ZIP Lambda function code..."

  source_dir="{{ service.build.context }}"
  output_dir="{{ service.environment.collection.config_files_path }}/build"
  output_file="$output_dir/{{ service.instance_name }}_lambda_function.zip"

  if [ -d "$source_dir" ]; then
    echo "Source is a directory: $source_dir"
    (cd "$source_dir" && zip -r "$output_file" .)
  elif [ -f "$source_dir" ]; then
    echo "Source is a file: $source_dir"
    base_name=$(basename "$source_dir")
    dir_name=$(dirname "$source_dir")
    (cd "$dir_name" && zip -r "$output_file" "$base_name")
  else
    echo "Error: Source path is not valid: $source_dir"
    exit 1
  fi

  if [ $? -eq 0 ]; then
    echo "ZIP file created successfully at $output_file"
  else
    echo "Error creating ZIP file"
    exit 1
  fi
}
