#!/usr/bin/env bash

set -e

OnError()
{
    echo "Failed."
}

trap OnError ERR

pushd "$(dirname "$0")" &> /dev/null
declare topdir="$PWD"
popd &> /dev/null


# check arguments

if [[ $# -ne 1 || "$1" == "-"* ]]
then
    echo "$(basename "$0")  DIRECTORY"
    echo ""
    echo "Install DIRECTORY as a package of astrometry_net_data."
    echo ""
    echo "This script can only be used for astrometry_net_data provided by the"
    echo " distributor of the pipeline binary."
    exit 1
fi

source "$topdir"/bashrc
setup-eups
setup meas_astrom

# get $product_dir from the arguments

declare product_dir="$1"

if [[ ! -e "$product_dir" ]]
then
    echo "error: the given path does not exist."
    exit 1
fi

# get the full path for $product_dir

pushd "$product_dir" &> /dev/null
product_dir="$PWD"
popd &> /dev/null

# $product_dir may be the parent directory of astrometry_net_data/
# In that case, we append "astrometry_net_data" to $product_dir

if [[ "$product_dir" != *"astrometry_net_data"* ]]
then
    if [[ -e "$product_dir/astrometry_net_data" ]]
    then
        product_dir="$product_dir/astrometry_net_data"
    else
        echo "error: the argument is not a path to astrometry_net_data"
        exit 1
    fi
fi

# It may be that $product_dir does not specify $product_ver.
# In that case, we append $product_ver to $product_dir

if [[ "$(basename "$product_dir")" == astrometry_net_data ]]
then
    declare dirs=("$product_dir"/*)
    if [[ ${#dirs[@]} -gt 1 ]]
    then
        echo "error: the given path is ambiguous. Specify one of:"
        for((i = 0; i < ${#dirs[@]}; ++i))
        do
            echo "${dirs[i]}"
        done
        exit 1
    fi
    if [[ ${#dirs[@]} -eq 0 ]]
    then
        echo "error: the given path does not contain valid astrometry_net_data."
        exit 1
    fi

    product_dir="${dirs[0]}"
fi

declare product_ver="$(basename "$product_dir")"
declare product_name="$(basename "$(dirname "$product_dir")")"

# It may be that $product_dir is a child directory of the desired directory.
# In that case, we go up the hierarchy.

while [[ "$product_name" != "astrometry_net_data" ]]
do
    if [[ "$product_name" == "/"*
    ||    "$product_name" == "."
    ||    "$product_name" == ""
    ]]
    then
        echo "Internal error ($LINENO): if you see this error, report it."
        exit 1
    fi

    product_dir="$(dirname "$product_dir")"
    product_ver="$(basename "$product_dir")"
    product_name="$(basename "$(dirname "$product_dir")")"
done

echoexec()
{
    echo Executing "$@". Wait...
    "$@"
}

# remove cache directory if exists, because it would do harm to "eups declare"
echoexec rm -rf "$HOME"/.eups

# eups declare: this is the core line of this script
echoexec eups declare -r "$product_dir" "$product_name" "$product_ver"

# execute andCache.py to prepare cache data
echoexec setup "$product_name" "$product_ver"
echoexec andCache.py

echo "OK"
