#!/bin/bash

SRC_DIR="${BASH_SOURCE%/*}"
source "$SRC_DIR/utils.sh"

TARGET="$1"
CONFIG="$2"
SPECIES_DATA_DIR="${TARGET%/*}"

JBROWSE_ARGS=(--force --target="$TARGET")

# Ensure that we use a local copy of genomic file when available
#
# Arguments:
#    URL: location of remote file
#    FILENAME: explicit name of remote file (if URL is opaque)
#    ARGS_REF: reference to an array of jbrowse CLI arguments
# Globals:
#    SPECIES_DATA_DIR: directory where species data files are expected
# Returns:
#    0, after extending the ARGS_REF array with file-related arguments
ensure_local() {
    local -r URL="$1"
    local -n args_ref="$3"

    # Use explicit filename if provided, otherwise the file part of the URL
    filename="${2:-${URL##*/}}"

    # Downloaded files are recompressed with bgzip(1), hence the --bgz
    # flag to normalize the file name with the .bgz extension
    local_file="$(normalize_filename --bgz "${filename}")"
    if [[ -e "${SPECIES_DATA_DIR}/${local_file}" ]]; then
	:
    # Another possibility is that the downloaded file was simply
    # unzipped (GTF files for example)
    elif [[ -e "${SPECIES_DATA_DIR}/${local_file/.bgz}" ]]; then
	local_file="${local_file/.bgz}"
    else
	args_ref=("$URL")
	echo "Using remote file $URL" >&2
	return
    fi
    echo "Using existing local file ${SPECIES_DATA_DIR}/${local_file}" >&2

    args_ref=(--load=inPlace)
    case "${local_file}" in
	*.fna.bgz)
	  args_ref+=(--type=bgzipFasta);;
        # Explicitly point to the index for bed/gff files
        *.bed.bgz)
          args_ref+=(--indexFile="${local_file}.csi");;
        *.gff.bgz)
          args_ref+=(--indexFile="${local_file}.csi");;
    esac
    args_ref+=("$local_file")
}

# List assemblies from a configuration file
# Arguments
#   Configuration file name
# Outputs:
#   Assemblies described on per line, with semicolon-separated fields
list_assemblies() {
    yq --no-doc '
    .assembly |
    [.url, .name, .displayName // "", .aliases // "aliases.txt", .fileName // ""] |
    # Strip empty lines
    select(any) |
    join(";")' "$1"
}

add_assemblies() {
    local -a file_args
    while IFS=';' read -r url name displayName aliases filename; do
	args=(--name="$name" --displayName="${displayName:-name}")
	if [[ -n "$aliases" ]]; then
	    args+=(--refNameAliases="$aliases")
	fi
	file_args=()
	ensure_local "$url" "$filename" file_args
	jbrowse add-assembly "${JBROWSE_ARGS[@]}" "${args[@]}" "${file_args[@]}"
    done < <(list_assemblies "$1")
}


# List tracks from a configuration file
# Arguments
#   Configuration file name
# Outputs:
#   One line per track, with semicolon-separated fields
list_tracks () {
    yq --no-doc '
    .assembly.name as $asm |
    .tracks[] |
    select(.addTrack != false) |
    [.url, .name, $asm, .fileName // ""] |
    # Prune empty lines
    select(any) |
    join(";")
    ' "$1"
}

add_tracks () {
    local -a file_args
    # jbrowse add-track expects target to exist, unlike add-assembly
    # See: https://github.com/GMOD/jbrowse-components/issues/4334
    [[ -e "$TARGET" ]] || echo '{}' > "$TARGET"
    while IFS=';' read -r url name assembly filename; do
	file_args=()
	ensure_local "$url" "$filename" file_args
	jbrowse add-track "${JBROWSE_ARGS[@]}" --name="${name}" --assemblyNames=${assembly}  "${file_args[@]}"
    done < <(list_tracks "$1")
}

add_hubs () {
    while IFS=';' read -r url name;
    do
	if [[ -n "$url" ]];
	then
	    jbrowse add-connection "${JBROWSE_ARGS[@]}" --name="$name" --connectionId="${name// /_}" "$url"
	fi
    done < <(yq '.hubs[] | [.url, .name] | join(";")' "$1")
}

main () {
    add_assemblies "$1"
    add_tracks "$1"
    add_hubs "$1"
}

if [[ ${BASH_SOURCE[0]} == "$0" ]];
then
   [[ -f "$CONFIG" ]] && { main "$CONFIG" |& grep -v 'node'; } || echo "Non existing file: $CONFIG"
fi
