#!/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 [ $# -ne 1 ]; then
    echo "[-] Takes one (1) argument:"
    echo "    <name> = name of virtualenv to make for current folder"
    return
fi

name=$1
venv=$VENVDIR/$name

if [ -d $venv ]; then
    echo "[-] Venv '$name' already exists in '$VENVDIR'."
    return
fi

echo
echo "Make sure you only call 'add' from *within* the directory you"
echo "wish to make into a virtual environment.  Calling 'add' will"
echo "create a '$VENVLABEL' file in your current directory."
read -p "Are you sure? [y/n] " -n 1 -r
echo    # (optional) move to a new line
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    echo "Stopping."
    return
fi

if [ -f $VENVLABEL ]; then
    echo
    echo "WARNING: There is already a '$VENVLABEL' file in this directory!"
    echo "Performing this operation will overwrite the file!"
    read -p "Are you sure? [y/n] " -n 1 -r
    echo    # (optional) move to a new line
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        echo "Stopping."
        return
    fi
fi

echo "[ ] Creating '$VENVLABEL'..." \
&& echo "$name" > $VENVLABEL \
&& echo "[ ] Creating virtualenv..." \
&& mkdir $venv \
&& virtualenv $venv \
&& echo "[ ] Activating virtualenv..." \
&& . $venv/bin/activate \
&& echo "[+] Now working on '$name' venv." \
|| echo "[-] Something went wrong -- permissions error?"
