#!/bin/bash

PROJECT_ID=fcon_1000

get_experiment_scans()
{

    session_id=$1
    experiment_label=$2
    experiment_uri=$3

    if ! scans=`curl -s \
                     -S \
                     --cookie JSESSIONID=$session_id \
                     "$XNAT_URL$exp_uri/scans?format=csv&columns=ID,URI"`
    then
        echo "$progname: error getting scans for $exp_label" >&2
        return 1
    fi

    # curl will return 0 even if the server returns an error, so we check the 
    # output itself
    first_line=`echo "$scans" | head -1`
    if [ "$first_line" != '"xnat_imagescandata_id","ID","URI"' ]
    then
        echo "$progname: error getting scans for $exp_label" >&2
        return 1
    fi

    while read id scan_name scan_uri
    do

        echo $scan_name $scan_uri

            # skip the header, strip the quotes, and delmit by a space
    done < <( echo "$scans" | tail -n +2 | tr -d '"' | tr , ' ' )

    return 0

} # end get_experiment_scans()

progname=`basename $0`

if ! type -P curl > /dev/null
then
    echo "$progname: can't find curl, bailing out" >&2
    exit 1
fi

if [ -z "$XNAT_URL" ]
then
    echo "$progname: XNAT_URL is not set; bailing out" >&2
    exit 1
fi

# strip trailing slashes (XNAT cares if there are double slashes in the URL)
XNAT_URL=`echo $XNAT_URL | sed 's+/*$++'`

if [ -z "$XNAT_USER" ]
then
    echo "$progname: XNAT_USER is not set; bailing out" >&2
    exit 1
fi

if [ -z "$XNAT_PASSWORD" ]
then
    echo "$progname: XNAT_PASSWORD is not set; bailing out" >&2
    exit 1
fi

if ! session_id=`curl -s \
                      -S \
                      -u $XNAT_USER:$XNAT_PASSWORD \
                      $XNAT_URL/data/JSESSION`
then
    echo "$progname: error starting XNAT session" >&2
    exit 1
fi

# curl may return 0 even if the server returned an error, so we check the form 
# of the session ID here
if [ `echo "$session_id" | wc -c` -ne 33 ]
then
    echo "$progname: error getting session ID" >&2
    exit 1
fi

if ! experiments=`curl -s \
                       -S \
                       --cookie JSESSIONID=$session_id \
                       "$XNAT_URL/data/projects/$PROJECT_ID/experiments?format=csv&columns=label,URI"`
then
    echo "$progname: error getting experiments" >&2
    return 1
fi

# curl will return 0 even if the server returns an error, so we check the 
# output itself
first_line=`echo "$experiments" | head -1`
if [ "$first_line" != '"xnat:subjectassessordata/id","label","URI"' ]
then
    echo "$progname: error getting experiments" >&2
    exit 1
fi

n_subjects=$((`echo "$experiments" | wc -l` - 1))
n=0
while read id exp_label exp_uri
do

    n=$(($n+1))
    echo $n/$n_subjects $exp_label
    scans=`get_experiment_scans $session_id $exp_label $exp_uri` || exit 1
    while read scan_name scan_uri
    do

        # special case: misspelled "skullstripped"
        if [ $scan_name = AnnArbor_sub47191_anat_mprage_skulstripped.nii.gz ]
        then
            new_name=anat_mprage_skullstripped
        elif [ $scan_name = ${exp_label}_anat_mprage_skullstripped.nii.gz ]
        then
            new_name=anat_mprage_skullstripped
        elif [ $scan_name = ${exp_label}_anat_mprage_anonymized.nii.gz ]
        then
            new_name=anat_mprage_anonymized
        elif [ $scan_name = ${exp_label}_func_rest.nii.gz ]
        then
            new_name=func_rest
        elif [ $scan_name = ${exp_label}_func_1_rest.nii.gz ]
        then
            new_name=func_1_rest
        elif [ $scan_name = ${exp_label}_func_2_rest.nii.gz ]
        then
            new_name=func_2_rest
        elif [ $scan_name = ${exp_label}_func_3_rest.nii.gz ]
        then
            new_name=func_3_rest
        elif [ $scan_name = ${exp_label}_func_4_rest.nii.gz ]
        then
            new_name=func_4_rest
        else
            echo "    $scan_name: skipping"
            continue
        fi

        echo "    $scan_name -> $new_name"

        if ! curl -s \
                  -S \
                  -o /tmp/fcon_1000_scan.xml \
                  --cookie JSESSIONID=$session_id \
                  $XNAT_URL$scan_uri
        then
            echo "$progname: error getting XML for $scan_name" >&2
            exit 1
        fi

        # curl will return 0 even if the server returns an error, so we check 
        # the output itself
        first_line=`head -1 /tmp/fcon_1000_scan.xml`
        if [ "$first_line" != '<?xml version="1.0" encoding="UTF-8"?>' ]
        then
            echo "$progname: error getting XML for $scan_name" >&2
            exit 1
        fi

        sed "s/ID=\"$scan_name\"/ID=\"$new_name\"/" \
            < /tmp/fcon_1000_scan.xml \
            > /tmp/fcon_1000_scan_fixed.xml

        curl --data-binary @/tmp/fcon_1000_scan_fixed.xml \
             -X PUT \
             --cookie JSESSIONID=$session_id \
             $XNAT_URL$scan_uri

        rm /tmp/fcon_1000_scan.xml /tmp/fcon_1000_scan_fixed.xml

    done < <( echo "$scans" )

        # skip the header, strip the quotes, and delmit by a space
done < <( echo "$experiments" | tail -n +2 | tr -d '"' | tr , ' ' )

exit 0

# eof
