#!/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

    which curl; curl_exists=$?
    if [ $curl_exists -ne 0 ]; then
        echo -e \\nWarning: Cannot find curl binary, skipping build status webhook...\\n
    else
        build_status=${1:-$COHERENCE_BUILD_STATUS}
        coherence_build_status=${build_status:-failed}
        curl -X PUT -H "Content-Type: application/json" \
        -d '{"token": "{{ stage.provider_token }}", "status": "'"$coherence_build_status"'"}' \
        {{ stage.callback_url }}; webhook_status=$?

        if [ $webhook_status -ne 0 ]; then
            echo -e \\nBuild status webhook failed.
            exit 0
        else
            echo -e \\nBuild status webhook succeeded.
        fi
    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 coherencebuilder || docker buildx create --name coherencebuilder --use
    docker buildx build {% for variable in service.environment_items %}--build-arg {{ variable.name }}={{ 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
        # Define the installation directory
        INSTALL_DIR="$HOME/.local/bin"

        # Create the installation directory if it does not exist
        mkdir -p "$INSTALL_DIR"

        # Download Nixpacks
        NIXPACKS_URL="https://github.com/railwayapp/nixpacks/releases/latest/download/nixpacks-linux-x64"
        NIXPACKS_BIN="$INSTALL_DIR/nixpacks"

        # Download the Nixpacks binary
        curl -L "$NIXPACKS_URL" -o "$NIXPACKS_BIN"

        # Make the binary executable
        chmod +x "$NIXPACKS_BIN"

        # Check if the installation was successful
        if ! "$NIXPACKS_BIN" --version &> /dev/null
        then
            echo "Failed to install Nixpacks. Please install it manually."
            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") }} \
    {% if service.command %} --start-cmd "{{ service.command }}" \{% endif %}
    {% for variable in service.environment_items %}--env {{ variable.name }}={{ 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 %}