#!/bin/bash
## compose: no-hooks

if [ -z "$SERVICE_DATASTORE" ]; then
    echo "This script is meant to be run through 'compose' to work properly." >&2
    exit 1
fi


version=0.1
usage="$exname [-h|--help] [DBNAME]"
help="
USAGE:

$usage

DESCRIPTION:

Drop odoo database DBNAME. If DBNAME is not provided, it'll take the
default odoo database from the ${DARKCYAN}postgres-database${NORMAL} relation of
current service.

EXAMPLES:

  $exname
  $exname odoo2

"


dbname=
while [ "$1" ]; do
    case "$1" in
        "--help"|"-h")
            print_help >&2
            exit 0
            ;;
        --*|-*)
            err "Unexpected optional argument '$1'"
            print_usage >&2
            exit 1
            ;;
        *)
            [ -z "$dbname" ] && { dbname=$1 ; shift ; continue ; }
            err "Unexpected positional argument '$1'"
            print_usage >&2
            exit 1
        ;;
    esac
    shift
done


db_drop() {
    local dbname="$1"
    (
        switch_to_relation_service postgres-database

        set +e
        . lib/common
        set -e

        ensure_db_docker_running || exit 1

        if db_has_database "$dbname"; then
            info "Found a postgres database '$dbname' and deleting it."
            PGM rm -f "$dbname" || exit 1
        else
            info "No postgres database '$dbname' found."
        fi

    ) || exit 1

    if [ -d "$SERVICE_DATASTORE"/var/lib/odoo/filestore/"$dbname" ]; then
        rm -rf "$SERVICE_DATASTORE"/var/lib/odoo/filestore/"$dbname" >&2 || exit 1
        info "Deleted filestore for database '$dbname'."
    else
        info "No filestore for database '$dbname' found."
    fi
}


if [ -z "$dbname" ]; then

    ##
    ## Fetch default dbname in relation to postgres-database
    ##

    ## XXXvlab: can't get real config here
    if ! read-0 ts _ _ < <(get_service_relation "$SERVICE_NAME" "postgres-database"); then
        err "Couldn't find relation ${DARKCYAN}postgres-database${NORMAL}."
        exit 1
    fi

    relation_file=$(get_relation_data_dir "$SERVICE_NAME" "$ts" "postgres-database") || {
        err "Failed to find relation file"
        exit 1
    }

    postgres_config=$(cat "$relation_file"/data) || exit 2

    dbname="$(e "$postgres_config" | shyaml get-value dbname)" || {
        err "Couldn't retrieve information of ${DARKCYAN}mysql-database${NORMAL}'s relation."
        exit 1
    }
fi

set -e

## Ensure odoo is launched
service_def=$(get_compose_service_def "$SERVICE_NAME")

## XXXvlab: should be moved to lib
CONFIG=$SERVICE_CONFIGSTORE/etc/odoo-server.conf
ADMIN_PASSWORD=$(echo "$service_def" | shyaml -q get-value options.admin-password) || {
    if [ -e "$CONFIG" ]; then
        ADMIN_PASSWORD=$(grep ^admin_passwd "$CONFIG" | sed -r 's/^admin_passwd\s+=\s+(.+)$/\1/g')
    fi
    if [ -z "$ADMIN_PASSWORD" ]; then
        err "Could not find 'admin-password' in $SERVICE_NAME service definition nor in config file."
        exit 1
    fi
}

container_network_ip=$(get_healthy_container_ip_for_service "$SERVICE_NAME" 8069 4) || {
    err "Please ensure that $DARKYELLOW$SERVICE_NAME$NORMAL is running before using '$exname'."
    exit 1
}

container_ip=${container_network_ip##*:}
container_network=${container_network_ip%%:*}


DEFAULT_CURL_IMAGE=${DEFAULT_CURL_IMAGE:-docker.0k.io/curl}


cmd=(
    docker run -i --rm --network "$container_network"
        "$DEFAULT_CURL_IMAGE"
        -sS
        -X POST
        -F "master_pwd=${ADMIN_PASSWORD}"
        -F "name=${dbname}"
        http://${container_ip}:8069/web/database/drop
)
## XXXvlab: contains password, left only for advanced debug
#echo "${cmd[@]}" >&2


out=$("${cmd[@]}") || {
    errlvl="$?"
    if [ "$errlvl" == "28" ]; then
        ## Curl timeout
        warn "Standard method through curl timed out. Trying manual drop of database."
        db_drop "$dbname" || exit 1
        exit 0
    else
        die "Posting to odoo drop API through curl was unsuccessfull ($errlvl)."
    fi
}

if [[ "$out" == *"<html>"* ]]; then
    errmsg=$(echo "$out" | grep -m1 "alert-danger") ||
        errmsg=$(echo "$out" | grep -m1 "errormsg") ||
        errmsg=$(echo "$out" | grep -m1 "<title>")
    errmsg="${errmsg#*>}"
    errmsg="${errmsg%%<*}"
    if [ -n "$errmsg" ]; then
        errmsg=$(echo "$errmsg" | recode html..utf8)
        if [[ "$errmsg" == "psycopg2.OperationalError: FATAL:  database \"$dbname\" does not exist" ]]; then
            warn "Received error we can probably ignore."
        elif [[ "$errmsg" == "KeyError: 'ir.http'" ]] ||
             [[ "$errmsg" == \
                 "psycopg2.ProgrammingError: relation \"base_registry_signaling\" already exists" ]]; then
            ## Hooks must have created an empty database, messing up things
            warn "Standard method failed as if postgres db was empty but existing."
            echo "  Trying manual drop of database.." >&2
            db_drop "$dbname"  || exit 1 ## Let's do it the legacy way !
        else
            die "$errmsg"
        fi
    else
        die "Unexpected output. Drop probably failed."
    fi
else
    info "Dropped odoo database '$dbname'."
fi >&2