#!/bin/bash

if ! command -v bash >/dev/null 2>&1; then
    echo "Bash not found. Exiting."
    exit 1
fi


{% block shared_functions %}
run_pre_build_commands () {
    echo `aws --version`
    {% if service %}
    mkdir -p ~/.docker/cli-plugins
    cp /usr/local/bin/docker-buildx ~/.docker/cli-plugins/docker-buildx
    {% endif %}
}

login_to_registries () {
    echo -e \\nLogging into Amazon ECR...\\n
    aws ecr get-login-password --region {{ environment.collection.region }} | \
    docker login -u AWS --password-stdin {{ service.image_registry_url().split('/')[0] }}
}

run_install_commands () {
    echo "install..."
}

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
}
{% endblock %}

{% block render_functions %}
{% endblock %}

{% block build_functions %}
{% if service.build %}
build_{{ service.name }}_image () {
{% if builder.file_exists(service.build.dockerfile) or (not service.build.dockerfile_is_default) %}
    echo -e "\\nBuilding from dockerfile...\\n"
    docker buildx inspect {{ service.name }}builder || docker buildx create --name {{ service.name }}builder --use
    docker buildx build {% for variable in service.environment_items %}--build-arg {{ variable.name }}="$(echo -en '{{ variable.value }}')"  {% endfor %}\
    --cache-to=type=inline \
    --cache-from=type=registry,ref={{ service.image_for_tag("latest") }} \
    --push \
    -t {{ service.image_for_tag("latest") }} \
    {% if builder.tag_for_service(service.name) %}-t {{ service.image_for_tag(builder.tag_for_service(service.name)) }}{% endif %} \
    -f {{ service.build.dockerfile }} \
    {{ service.build.context }}
{% else %}
    echo -e "\\Building with nixpacks...\\n"

    # Check if Nixpacks is installed
    if ! command -v nixpacks &> /dev/null
    then
        curl -sSL https://nixpacks.com/install.sh | bash
        if ! command -v nixpacks &> /dev/null
        then
            echo "Failed to find Nixpacks. Please install it manually - see https://nixpacks.com/docs/install."
            exit 1
        fi
    else
        NIXPACKS_BIN=$(command -v nixpacks)
    fi

    nixpacks build {{ service.build.context }}/ --inline-cache \
    --cache-from {{ service.image_for_tag("latest") }} \
    --name {{ service.image_for_tag(builder.tag_for_service(service.name) or "latest") }} \
    --start-cmd "{{ service.command or 'sleep 1' }}" \
    {% for variable in service.environment_items %}--env {{ variable.name }}="$(echo -en '{{ variable.value }}')"  {% endfor %}
    {% if builder.tag_for_service(service.name) %}
    docker tag {{ service.image_for_tag(builder.tag_for_service(service.name)) }} {{ service.image_for_tag("latest") }}
    {% endif %}
{% endif %}
}

push_{{ service.name }}_image_tags () {
    echo -e "\\nPushing docker images...\\n"
    {% if not service.image %}
    docker push {{ service.image_for_tag("latest") }}
    {% if builder.tag_for_service(service.name) %}
    docker push {{ service.image_for_tag(builder.tag_for_service(service.name)) }}
    {% endif %}
    {% else %}
    echo -e \\nNothing to do, skipping...
    {% endif %}
}
{% else %}
verify_{{ service.name }}_image_exists () {
    echo -e "\\nSkipping image build - using existing image."
    echo -e "\\nVerifying image exists...\\n"
    docker manifest inspect {{ service.image_for_tag(builder.tag_for_service(service.name)) }}; inspect_result=$?
    if [ $inspect_result -ne 0 ]; then exit $inspect_result; fi
}
{% endif %}

{% endblock %}