#!/usr/bin/env bash
set -eo pipefail
shopt -s expand_aliases
alias podman="podman --cgroup-manager=cgroupfs --events-backend=file"

function clean_before_exit {
    # delay before exiting, so stdout/stderr flushes through the logging system
    pkill -15 caddy
    pkill -15 podman
    sleep 3
}
trap clean_before_exit EXIT

function waiting_process {
    echo -e "\\033[32m---> Waiting $1 running.\\033[0m"
    for i in {0..4}; do
        if ps -C "$1" 1>/dev/null ; then
            sleep 1
            echo -e "\\033[32m---> Process $1 started.\\033[0m"
            break
        else
            if [[ $i == 3 ]]; then
                echo -e "\\033[31m---> Process $1 failed.\\033[0m"
                exit 1
            else
                sleep 3
            fi
        fi
    done
}

# Start podman service
export DOCKER_PORT=1234
export DOCKER_HOST=tcp://127.0.0.1:${DOCKER_PORT}

log_level="error"
if [[ "${DRYCC_DEBUG}" ]]; then
    log_level="debug"
    unset DRYCC_DEBUG
fi

registries="/etc/imagebuilder/registries.conf"
if [ -f "${registries}" ]; then
    cat "${registries}" > /etc/containers/registries.conf
fi

podman system service --time 0 tcp:0.0.0.0:${DOCKER_PORT} &

waiting_process podman
if [[ -n "${TAR_PATH}" ]]; then
    get_object
    tar -xzf /tmp/app.tgz -C /app/ && unset TAR_PATH
fi

pack_builder="docker.io/drycc/buildpacks:20"
if [[ -f .pack-builder ]]; then
    pack_builder=$(< .pack-builder tr -d '[:space:]')
fi

# Get registry and login
if [[ "${DRYCC_REGISTRY_LOCATION}" == "off-cluster" ]] ; then
    registry="${DRYCC_REGISTRY_HOSTNAME}/${DRYCC_REGISTRY_ORGANIZATION}"
    podman login \
        --username "${DRYCC_REGISTRY_USERNAME}" \
        --password "${DRYCC_REGISTRY_PASSWORD}" \
        "${DRYCC_REGISTRY_HOSTNAME}" \
        --tls-verify=false > /dev/null
else
    # Start registry proxy
    registry="${DRYCC_REGISTRY_PROXY_HOST}:${DRYCC_REGISTRY_PROXY_PORT}"
    if [[ ${log_level} == "debug" ]] ; then
        output="/dev/stdout"
    else
        output="/dev/null"
    fi
    caddy reverse-proxy \
        --from ":${DRYCC_REGISTRY_PROXY_PORT}" \
        --to "${DRYCC_REGISTRY_SERVICE_HOST}:${DRYCC_REGISTRY_SERVICE_PORT}" \
        > "${output}" 2>&1 &
    waiting_process caddy
    podman login \
        --username drycc \
        --password drycc \
        --tls-verify=false "${registry}" \
        > /dev/null
fi

# Get image name and image tag
image_name=$(echo "${IMG_NAME}" | awk -F ':' '{print $1}')
image_tag=$(echo "${IMG_NAME}" | awk -F ':' '{print $2}')
image_repo="${registry}/${image_name}:${image_tag}"
image_cache_repo="${registry}/${image_name}:cache"
image_latest_repo="${registry}/${image_name}:latest"

# Building
if [[ "${DRYCC_STACK}" == "container" ]] ; then
    echo "---> Building container"
    if [[ $log_level == "debug" ]] ; then
        podman build --tag"${image_repo}" --network host .
        podman push "${image_repo}" --tls-verify=false
    else
        podman build --quiet --tag "${image_repo}" --network host .
        podman push "${image_repo}" --quiet --tls-verify=false
    fi
else
    echo "---> Building pack"
    echo "---> Using builder ${pack_builder}"
    pack_command="pack build ${image_repo} \
            --builder ${pack_builder} \
            --docker-host ${DOCKER_HOST} \
            --previous-image ${image_latest_repo} \
            --trust-builder \
            --publish \
            --cache-image ${image_cache_repo} \
            --tag ${image_latest_repo} \
            --network host \
            --verbose"
    if [[ $log_level == "debug" ]] ; then
        pack_command="$pack_command --verbose"
    fi
    if [[ -f .clear-cache ]]; then
        pack_command="$pack_command --clear-cache"
    fi
    $pack_command
fi