#!/bin/bash

# script should fail when any process returns non zero code
set -e

function generate_default_app_name() {
    local branch_name=$(git rev-parse --abbrev-ref HEAD)
    local branch_name_slug=$(echo "$branch_name" | sed -e 's/[^[:alnum:]]/-/g' | tr -s '-' | tr A-Z a-z)

    local default_app_name="vbv-$branch_name_slug"

    # shorten default_app_name to 32 characters
    if ((${#default_app_name} > 32)); then
        local hash="$(echo -n "$default_app_name" | md5sum | cut -c1-4)"
        default_app_name=$(echo -n "${default_app_name:0:28}-${hash}")
    fi

    # remove multiple dashes and make sure it does not end with a dash
    default_app_name=$(echo "$default_app_name" | sed -E 's/-+/-/g')
    default_app_name=$(echo "$default_app_name" | sed 's/-\+$//')

    echo "$default_app_name"
}

# take app name as first argument or use the default generated app name
APP_NAME=${1:-$(generate_default_app_name)}

# VITE_* variables need to be present at build time
export VITE_APP_ENVIRONMENT="dev-$APP_NAME"

if [[ "$APP_NAME" == "myvbv-stage" ]]; then
    export VITE_OAUTH_API_BASE_URL="https://vbvtst.b2clogin.com/vbvtst.onmicrosoft.com/b2c_1_signupandsignin/oauth2/v2.0/"
    export VITE_APP_ENVIRONMENT="stage-caprover"
elif [[ "$APP_NAME" == prod* ]]; then
    export VITE_OAUTH_API_BASE_URL="https://edumgr.b2clogin.com/edumgr.onmicrosoft.com/b2c_1_signupandsignin/oauth2/v2.0/"
    export VITE_APP_ENVIRONMENT=$APP_NAME
fi

echo "Deploy to $APP_NAME"

# create client for django
npm run build
IT_APP_ENVIRONMENT=local python server/manage.py collectstatic --no-input

if [[ "$APP_NAME" == "prod-azure" ]]; then
    # build and push azure docker container
    docker build --platform linux/amd64 -f compose/django/Dockerfile -t iterativ/vbv-lernwelt-django:azure .
    docker image push iterativ/vbv-lernwelt-django:azure
    # FIXME: It seems that in Azure we have to manually restart the container for now
    echo "https://my.vbv-afa.ch/" >/tmp/caprover_app_url.txt
else
    # create and push new docker container
    VERSION=$(git log -1 --pretty=%h)
    REPO="iterativ/vbv-lernwelt-django"
    LATEST="${REPO}:latest"
    BUILD_TIMESTAMP=$(date '+%F_%H:%M:%S')
    VERSION_TAG="${REPO}:$VERSION"
    docker build --platform=linux/amd64 -f compose/django/Dockerfile -t "$REPO" -t "$LATEST" -t "$VERSION_TAG" --build-arg VERSION="$VERSION" --build-arg BUILD_TIMESTAMP="$BUILD_TIMESTAMP" --build-arg GIT_COMMIT="$(git log -1 --format=%h)" .
    docker push "$VERSION_TAG"

    # caprover specific deployment
    APP_URL="$APP_NAME.control.iterativ.ch"

    echo "Checking if $APP_URL is available..."
    if ! curl --output /dev/null --silent --head --fail "$APP_URL"; then
        echo "HTTP request to $APP_URL did not return a 200 status code, so we need to create the caprover app"
        python caprover_cleanup.py -a "$APP_NAME*" --automated
        python caprover_create_app.py -a "$APP_NAME"
    fi

    # deploy to caprover, explicitly use the version tag... so if there is a mismatch you get an error message
    caprover deploy -h https://captain.control.iterativ.ch -a "$APP_NAME" -i docker.io/"$VERSION_TAG"

    if [ -n "$CI" ]; then
        echo "Running within Bitbucket Pipelines"
        export CAPROVER_APP_URL="$APP_URL"
        echo "https://$CAPROVER_APP_URL" >/tmp/caprover_app_url.txt
    fi
fi
