#!/bin/bash

# make sure script is being run as source
if [ "${BASH_SOURCE[0]}" == "${0}" ]; then
    echo "[-] You must source this script to run it."
    exit
fi

########################################

# make sure environment variables exist
if [ -z "$VENVDIR" ]; then
    echo "[!] Must define '\$VENVDIR' as environment variable (default ~/.venvs/)."
fi

if [ -z "$WORKDIR" ]; then
    echo "[!] Must define '\$WORKDIR' as environment variable."
fi

if [ -z "$VENVLABEL" ]; then
    echo "[!] Must define '\$VENVLABEL' as environment variable (default 'venv.txt')."
fi

if [ -z "$VENVDIR" ] || [ -z "$WORKDIR" ] || [ -z "$VENVLABEL" ]; then
    return
fi

########################################

if [ ! -d $VENVDIR ]; then
    echo "[!] Venv directory '$VENVDIR' does not exist!!!"
    echo "[!] Please fix this manually!"
    return
fi

########################################

if [ $# -ne 0 ]; then
    echo "[-] Takes no arguments."
    return
fi

if [ ! -f $VENVLABEL ]; then
    echo "[-] No '$VENVLABEL' file found."
    return
fi

name=`cat $VENVLABEL`
venv=$VENVDIR/$name

if [ ! -d $venv ]; then
    echo "[-] Venv '$name' not found in '$VENVDIR'"
    return
fi

echo "[ ] Activating virtualenv..." \
&& . $venv/bin/activate \
&& echo "[+] Now working on '$name' venv." \
|| echo -e "[-] There was a problem with your '$VENVLABEL' file!\nPlease make sure it is a valid filename!"
return
