#!/bin/bash 

if [ "x$MDQ_HOME" = "x" ] ; then
    source ./SETUP.bash
    if [ $? != 0 ] ; then
	exit 1
    fi
fi


   
set -euo pipefail

if [ $# != 1 ] ; then
    echo "----" 1>&2
    echo "Usage: $0 <year>" 1>&2
    echo "----" 1>&2
    exit 1
fi

year=$1

download_script="dataset-download/DOWNLOAD-DATASET-WITH-NOHUP-$year.sh"

echo $PWD

if [ -x "$download_script" ] ; then

    # Get an array of pids if any are running, ... noting
    #   Caveat 1: ... if no retuned pids then pgrep return exit 1, so use || true to keep 'set -e' happy
    #   Caveat 2: ... the linux kernel caps process names at 15 chars, so name to look for is 'transmission-cl'
    existing_pids=($(pgrep -u "$USER" transmission-cl || true))

    if [ ${#existing_pids[@]} -gt 0 ] ; then
	echo "----"
	echo "There are existing transmission-cli processes running:"
	echo "  ${existing_pids[*]}"
	echo "----"
	echo ""


	read -r -p "Do you want to proceed? [y/N] " response

	if [[ "$response" =~ ^[Yy]$ ]]; then
	    echo "Continuing..."
	else
	    echo "Aborted"
	    exit 1
	fi
    fi
        
    cd dataset-download \
	&& ./DOWNLOAD-DATASET-WITH-NOHUP-$year.sh
else
    echo "----" 1>&2
    echo "Error: Failed to find execuable script for $year: " 1>&2 
    echo "  $download_script" 1>&2
    echo "----" 1>&2
    exit 1
fi

# so the process never finished
#
# The CLI tool does however print out progress of how much is downloaded, this can be monitored with:
#
#     egrep "^Processed:" nohup.out
#
# It also prints out a line when the download is completed.  A bit tricker to spot, so have a helper script
# for this:
#
#     ./CHECK-DOWNLOAD-COMPLETE.sh





# Unsuccessful attempt to include a marker that helps spot when the download is completed
#    && echo -w "----\nCOMPLETED\n----" \



