#!/usr/bin/env bash

set -x

files="$*"

function create_bin_file
{
tempfile=~/backshift.$$
cat << EOF > "$tempfile"
#!/usr/bin/env bash

if [ "\$#" = 0 ]
then
    "$which_python" "$prefix"/lib/backshift/backshift
else
    "$which_python" "$prefix"/lib/backshift/backshift "\$@"
fi

EOF
chmod 755 "$tempfile"
if cmp "$tempfile" "$bindir"/backshift > /dev/null 2>&1
then
    # No need to install the file - a version with the same content is already there.
    rm -f "$tempfile"
else
    sudo mv "$tempfile" "$bindir"/backshift
fi
}

if [ -d install-variables ]
then
    prefix=$(cat 'install-variables'/prefix-file)
    bindir=$(cat 'install-variables'/bindir-file)
    which_python=$(cat 'install-variables'/python-file)
    use_cython=$(cat 'install-variables'/use-cython-file)

    # mkdir -p "$bindir"
    # mkdir -p "$prefix"/lib/backshift

    # Install the pure python modules
    for file in $files
    do
        ./install-file --file "$file" --directory "$prefix"/lib/backshift/.
    done

    # Optionally install the Cython
    if [ "$use_cython" = "True" ]
    then
        ./build-one-rcm --use-installation-python
        # We remove the previous file to avoid segfaults if we reinstall during a backup
        if [ -f "$prefix"/lib/backshift/rolling_checksum_pyx_mod.so ]
        then
            sudo rm "$prefix"/lib/backshift/rolling_checksum_pyx_mod.so
        fi
        make rolling_checksum_pyx_mod.so
        ./install-file --file rolling_checksum_pyx_mod.so --directory "$prefix"/lib/backshift/.
        # This comes in through argv - we don't want it since we're doing the cython version
        if [ -f "$prefix"/lib/backshift/rolling_checksum_py_mod.py ]
        then
            sudo rm "$prefix"/lib/backshift/rolling_checksum_py_mod.py
        fi
    fi

    # Install some ancillary scripts
    for file in 'just-one' 'randomize' 'most-recent' 'find-backup' 'backshift-one' 'backshift-while'
    do
        ./install-file --file "$file" --directory "$bindir"/.
    done

    # Finally, create the frontend bash script and make it executable
    create_bin_file

else
    echo "$0: You must run ./configure before 'make install'" 1>&2
    exit 1
fi