#!/bin/bash

# This is a bash rc file for developing in the WC/LS (Wire-Cell
# Toolkit + LArSoft) Singularity container.

source /usr/local/ups/setup

# set this, but warning that calling "setup" with the "wirecell" UPS product will tromp on it.
export WIRECELL_PATH=/usr/local/share/wirecell/data:/usr/local/share/wirecell/cfg

export PS1='[wclsdev:$WIRECELL_VERSION]\u@\h:\w> '

# The locale sitch of the image is a bit fubar and this makes Perl
# angry.  Sorry, it's an ASCII world.
export LANG=C


if [ -z "$USER" ] ; then
    export USER=$(id -n -u)
fi

# the version string to use for the development "wirecell" UPS product
wclsdev_wcver="wclsdev"

wclsdev_upsdev=/usr/local/ups-dev
if [ -d $wclsdev_upsdev -a ! -d $wclsdev_upsdev/.upsfiles ] ; then
    echo "priming development UPS products area: $wclsdev_upsdev"
    cp -a /usr/local/ups/.up* $wclsdev_upsdev/
fi
PRODUCTS=$wclsdev_upsdev:$PRODUCTS


# Return a version for newest package
wclsdev-ups-version () {
    local pkg="${1:-larsoft}"
    ups list -aK+ "$pkg" | tail -1 | awk '{print $2}' | sed -e 's/"//g'
}

# Return the quals for a most reacent package
wclsdev-ups-quals () {
    local pkg="${1:-larsoft}"
    ups list -aK+ "$pkg" | tail -1 | awk '{print $4}' | sed -e 's/"//g'
}
    

# make some UPS product area, default to wirecell / dev
wclsdev-ups-declare () {
    local pkg="${1:-wirecell}"
    local ver="${1:-$wclsdev_wcver}"
    local upsdir="${wclsdev_upsdev}/${pkg}/${ver}/ups"

    if [ -d "$upsdir" ] ; then  # fixme: premature test?
        echo "wclsdev-ups-declare: already declared: $upsdir"
        return
    fi
    mkdir -p $upsdir

    local relver=$(PRODUCTS=/usr/local/ups wclsdev-ups-version $pkg)
    local relquals=$(PRODUCTS=/usr/local/ups wclsdev-ups-quals $pkg)

    cp "/usr/local/ups/${pkg}/${relver}/ups/${pkg}.table" "$upsdir"
    ups declare wirecell ${ver} \
        -f $(ups flavor) \
        -q ${relquals} \
        -r "${pkg}/${ver}" \
        -z $wclsdev_upsdev \
        -U ups  \
        -m "${pkg}.table"
    set +x
    
}

# configure WCT source for building.
wclsdev-wct-configure () {
    ver="${1:-$wclsdev_wcver}"
    if [ ! -f wcb ] ; then
        echo "wclsdev-wct-configure: must run from inside your WCT source area"
        return
    fi
    if [ "$WIRECELL_VERSION" != "dev" ] ; then
        echo "wclsdev-wct-configure: switching to \"$ver\" version of 'wirecell' UPS product"
        setup wirecell $ver -q $(wclsdev-ups-quals)
    fi
    ./wcb configure \
          --with-tbb=no \
          --with-jsoncpp="$JSONCPP_FQ_DIR" \
          --with-jsonnet="$JSONNET_FQ_DIR" \
          --with-eigen-include="$EIGEN_DIR/include/eigen3" \
          --with-root="$ROOTSYS" \
          --with-fftw="$FFTW_FQ_DIR" \
          --with-fftw-include="$FFTW_INC" \
          --with-fftw-lib="$FFTW_LIBRARY" \
          --boost-includes="$BOOST_INC" \
          --boost-libs="$BOOST_LIB" \
          --boost-mt \
          --prefix=$WIRECELL_FQ_DIR || return 1
    echo "wclsdev-wct-configure: will install to $WIRECELL_FQ_DIR"
    echo -e "\tready to run:\n\t./wcb -p --notests install"
}


# Initialize a development area.  This stops before initializing any
# source.  Warning: this modifies your environment.
wclsdev-init () {
    local base="$1";shift
    local lsver="${1:-$(wclsdev-ups-version larsoft)}"; shift
    local quals="${1:-$(wclsdev-ups-quals   larsoft)}"; shift
    local quals_="$(echo $quals | tr ':' '_')"

    if [ ! -d "$base" ] ; then
        mkdir "$base"
    else
        echo "wclsdev-init: reusing existing base: $base"
    fi
    pushd "$base" > /dev/null 2>&1

    echo "wclsdev-init: modifying your environment for mrb and larsoft $lsver -q $quals"
    export MRB_PROJECT=larsoft
    setup mrb
    setup larsoft "$lsver" -q "$quals"

    local localsetup="localProducts_larsoft_${lsver}_${quals_}/setup"
    if [ ! -f "$localsetup" ] ; then
        mrb newDev
    else
        echo "wclsdev-init: already inoculated with mrb: $localsetup"
    fi
    echo "wclsdev-init: modifying your environment for local dev products"
    source "$localsetup"
    popd > /dev/null 2>&1
}

    
# Add a source package to an development area.  You must has run
# wcldev-init first.
wclsdev-srcs () {
    local pkg="${1:-larwirecell}"; shift
    local tag="${1:-${USER}_wclsdev}"; shift
    local ver="${1:-$(wclsdev-ups-version $pkg)}"; shift

    if [ -z "$MRB_SOURCE" ] ; then
        echo "wclsdev-srcs: you must have run wclsdev-init first"
        return
    fi

    pushd "${MRB_SOURCE}" > /dev/null 2>&1
    if [ -d "$pkg" ] ; then
        echo "wclsdev-srcs: package source directory already exists"
        return
    fi
    mrb g "$pkg"
    cd "$pkg"
    local branch="${ver}-branch"
    local feat="feature/${tag}"
    if git branch -a | grep "\b${feat}\b" > /dev/null ; then
        echo "wclsdev-srcs: our feature exists, using it: $feat"
        git checkout "$feat"
    elif git branch -a | grep "\b$branch\b" > /dev/null ; then
        echo "wclsdev-srcs: our release branch exists, using it: $branch"
        git flow feature start "$tag" "$branch"
    else
        echo "wclsdev-srcs: creating release branch $branch and feature $tag"
        git checkout -b "$branch" "$ver"
        git flow feature start "$tag" "$branch"
    fi
    popd > /dev/null 2>&1
}


# Set up environment to use an existing development area
wclsdev-setup () {
    local base="${1:-$(pwd)}";shift
    pushd "$base"
    if [ ! -f "$base/srcs/CMakeLists.txt" ] ; then
        echo "wclsdev-setup: area is not inoculated: $base"
        echo -e "\ttry wclsdev-init?"
        popd
        return
    fi

    if [ $(ls localProducts_*/setup | wc -l) -gt 1 ] ; then
        echo "wclsdev-setup: ambiguity: more than one local products in $base"
        return
    fi

    echo "wclsdev-setup: modifying your environment for mrb and local products in $base"
    export MRB_PROJECT=larsoft
    setup mrb
    source localProducts_*/setup
    
    # this system is just utter crap
    if [ -f srcs/larwirecell/ups/product_deps ] ; then
        if [ -n "$(grep '^wirecell\b.*'$wclsdev_wcver srcs/larwirecell/ups/product_deps)" ] ; then
            echo "wclsdev-setup: you are using WCT $wclsdev_wcver, must 'unsetup wirecell' now"
            unsetup wirecell
        fi
    fi

    pushd build_*
    mrbsetenv
    popd

    echo "wclsdev-setup: leaving you in $(pwd)"

}

# Modify all product_deps files to set a different version for a package.
wclsdev-fsck-ups () {
    local base="${1:-$MRB_TOP}"; shift
    local pkg="${1:-wirecell}"; shift;
    local ver="${1:-$wclsdev_wcver}"; shift

    if [ ! -d "$base/srcs/" ] ; then
        echo "wclsdev-fsck-ups: this doesn't look like an mrb source area: $base"
        return
    fi

    for pd in $base/srcs/*/ups/product_deps
    do
        echo -e "\t$pd"
        sed  -e "s/^${pkg}\b.*/${pkg}\t${ver}/" -i $pd
    done

    echo "wclsdev-fsck-ups: before running 'mrbsetenv' you must run:"
    echo -e "\tunsetup $pkg"

}    

# The "wirecell" UPS product constantly steps on this variable, so
# here we try to find a more sane choice.  It guesses a few likely
# spots.  Note: take care when adding multiple entries with nominally
# the same files.  Unlike PATH, Jsonnet let's the *last* match win.
wclsdev-path () {
    if [ -n "$WIRECELL_PATH" ] ; then
        echo "wclsdev-path: clobbering WIRECELL_PATH=$WIRECELL_PATH" 1>&2
    fi
    local wcd=""
    local wcc=""
    local base=""

    # check in some opinionated locations, take first found
    for base in . /usr/local/share/wirecell /usr/local/ups-dev $HOME/dev/wct/src
    do
        for prefix in "" "wire-cell-"
        do
            local maybe="$base/${prefix}data" 
            if [ -z "$wcd" -a -d "$maybe" ] ; then
                wcd="$maybe"
            fi
            maybe="$base/${prefix}cfg"
            if [ -z "$wcc" -a -d "${maybe}/pgrapher" ] ; then
                wcc="$maybe"
            fi
        done
    done

    export WIRECELL_PATH="$wcd:$wcc"
    echo "WIRECELL_PATH=$WIRECELL_PATH"
}

# Toggle a git URL to ssh or http, given as first arg.  Second arg may
# be a directory o.w. current directory is assumed to be in git repo's
# working directory.
wclsdev-set-fnal-git-url () {
    scheme="$1" ; shift
    pushd ${1:-.} > /dev/null 2>&1

    # get project name.
    local pname=$(git remote get-url origin | sed -e 's|.*/projects/\(.*\)$|\1|')
    if [ "$scheme" = "ssh" ] ; then
        git remote set-url origin "ssh://p-${pname}@cdcvs.fnal.gov/cvs/projects/${pname}"
    elif [ "$scheme" = "http" ] ; then
        git remote set-url origin "http://cdcvs.fnal.gov/projects/${pname}"
    else
        echo "Unknown scheme: \"$scheme\""
        popd > /dev/null 2>&1
        return 1
    fi

    echo "Set git URL to:"
    git remote get-url origin    
    popd > /dev/null 2>&1
    
}
