#!/usr/bin/env bash
set -e

script=$(basename "$0")
version="1.0.1"

help() {
    echo
    echo "$script"
    echo
    echo 'Description: Restore Odoo database.'
    echo "Syntax: $script [-p|-d|-f|-h|-r|-n|-m|-V|help]"
    echo 'Example: $script -p secret -d odoo -f /tmp/odoo.sql -h https://odoo.example.com -r -m -n'
    echo 'options:'
    echo '  -p    Odoo master password. Defaults to \$ODOO_MASTER_PASSWORD env var and '\''admin'\''.'
    echo '  -d    Database name. Defaults to filename.'
    echo '  -f    Odoo database backup file. Defaults to '\''/var/tmp/odoo.zip'\''.'
    echo '  -h    Odoo host. Defaults to '\''http://localhost:8069'\''.'
    echo '  -r    Replace existing database.'
    echo '  -n    Neutralize database after restore.'
    echo '  -m    Database was moved.'
    echo '  -v    Show $script version.'
    echo "  help  Show $script manual."
    echo
}

if [[ "$1" == 'help' ]]; then
    help
    exit
fi

replace='false'
neutralize='false'
copy='true'
password=${ODOO_MASTER_PASSWORD:=odoo}
file=/var/tmp/odoo.zip
odoo_host=http://localhost:8069

while getopts ':p: :d: :f: :h: :r :n :m :V' opt; do
    case $opt in
        p) password="$OPTARG";;
        d) database="$OPTARG";;
        f) file="$OPTARG";;
        h) odoo_host="$OPTARG";;
        r) replace='true';;
        n) neutralize='true';;
        m) copy='false';;
        V) echo "$script version $version"
        exit 0
        ;;
        \?) echo "Invalid option -$OPTARG" >&2
        help
        exit;;
    esac
done

filename=$(basename -- "$file")
database=${database:="${filename%%.*}"}

[[ "$odoo_host" == http* ]]  || { echo "Parameter -h|host must start with 'http/s'" ; exit 1; }

if [[ "${file: -3}" =~ "zip" ]]; then
    unzip -q -t $file
fi

if $replace; then
    odoo-drop -p "$ODOO_MASTER_PASSWORD" -d "$database" -h "$odoo_host"
fi

echo "Requesting restore for Odoo database from $file to $database ..."

command="curl \
-F \"master_pwd=$password\"
-F \"name=$database\"
-F \"backup_file=@$file\""
if $neutralize; then
    command="$command -F \"neutralize_database=$neutralize\""
fi
if $copy; then
    command="$command -F \"copy=$copy\""
fi
command="$command ${odoo_host%/}/web/database/restore"

response=$(eval $command)

check=$(echo "$response" | { grep 'Redirecting...' || true; })
if [[ -n "$check" ]]; then
    echo "The restore for Odoo database $database has finished."
else
    echo "The restore for Odoo database $database failed with:"
    echo "$response" | grep error
    exit 1
fi
