#!/bin/bash

echo "Beginning ISStreamer Python Easy Installation!"
echo "                                  _________       "
echo "                               NN           NN    "
echo "                             N                 N  "
echo "                            N      NNNNNNN      N "
echo "                          N      NN       N      N"
echo "NNNNNNN                  N      N          N     N"
echo "N     N                 N      N           N     N"
echo "N     N               N       N            N     N"
echo "                                                  "
echo "NNNN NN            NNNNNNNN                NNNNNNN"
echo "N     N           N      N                 N     N"
echo "N     N          N      N                  N     N"
echo "N      N       NN      N                   NNNNNNN"
echo " N      NNNNNNN      N                            "
echo "  N                 N                             "
echo "    NN           NN                               "
echo "       ---------                                  "
echo "This may take a couple minutes to install, grab some coffee :)"
echo "But don't forget to come back, I'll have questions later!"
echo ""
INITIALSTATE_AUTH_SVC=${INITIALSTATE_AUTH_SVC:="auth"}
SUDO=''

# if this script is being run by root user
# then we need to modify file saving commands
# to make sure ownership is correct
if [ "$EUID" -eq 0 ]; then
	SUDO="sudo -u $SUDO_USER"
fi


function check_for_easy_install {
    if hash easy_install 2>/dev/null; then
        easy_install_version=$(easy_install --version)
        echo "Found easy_install: $easy_install_version"
    else
        echo "easy_install not found, installing now..."

        if hash apt-get 2>/dev/null; then
        	if [[ $1 -eq '-v' ]]; then
        		apt-get -y install python-setuptools
        	else
				apt-get -y install python-setuptools > /dev/null
        	fi
        else
        	echo "no apt-get, using curl..."
        	if [[ $1 -eq '-v' ]]; then
        		curl https://bootstrap.pypa.io/ez_setup.py -o - | python
        	else
        		curl https://bootstrap.pypa.io/ez_setup.py -o - | python > /dev/null
        	fi
        fi
    fi
}

function check_for_pip {
	if hash pip 2>/dev/null; then
		pip_version=$(pip --version)
		echo "Found pip: $pip_version"
		pip_version_array=(${pip_version//" "/ })
		pip_version_num=${pip_version_array[1]}
		pip_version_num_array=(${pip_version_num//./ })
		pip_major_version=${pip_version_num_array[0]}
		pip_minor=${pip_version_num_array[1]}
		pip_minor_version_array=(${pip_minor//"rc"/ })
		pip_minor_version=${pip_minor_version_array[0]}

		echo "pip major version: $pip_major_version"
		echo "pip minor version: $pip_minor_version"

	else
		echo "pip not found, installing now..."
		if [[ $1 -eq '-v' ]]; then
			easy_install pip
		else
			easy_install pip > /dev/null
		fi
	fi
}

function check_for_isstreamer {
	isstreamer=$(pip freeze | grep ISStreamer)
	if [ -z "$isstreamer" ]; then
		echo "ISStreamer not found, installing..."

		pip install ISStreamer
	else
		echo "ISStreamer found, updating..."

		pip install --upgrade ISStreamer
	fi

	isstreamer_version=$(python -c "import ISStreamer.version; print(ISStreamer.version.__version__)")


	if [[ $isstreamer_version == "" ]] ; then
		echo "No ISStreamer found..."
		exit 1
	else
		echo "Found ISStreamer: $isstreamer_version"
		isstreamer_version_array=(${isstreamer_version//" "/ })
		isstreamer_version_num=${isstreamer_version_array[0]}
		isstreamer_version_num_array=(${isstreamer_version_num//./ })
		isstreamer_major_version=${isstreamer_version_num_array[0]}
		isstreamer_minor=${isstreamer_version_num_array[1]}
		isstreamer_minor_version_array=(${isstreamer_minor//"rc"/ })
		isstreamer_minor_version=${isstreamer_minor_version_array[0]}

		echo "isstreamer major version: $isstreamer_major_version"
		echo "isstreamer minor version: $isstreamer_minor_version"
	fi
}

function download_script {
	echo "Please select which Initial State app you're using: "
	echo "1) app.initialstate.com"
	echo "2) [NEW!] iot.app.initialstate.com"
	echo -n "Enter choice 1 or 2: "
	read app_version < /dev/tty

	if [ "$app_version" = "1" ]; then
		echo -n "Enter app.initialstate.com user email: "
		read username < /dev/tty
		echo -n "Enter app.initialstate.com password [input hidden]: "
		read -s password < /dev/tty
		echo ""

		if [ -z "$example_location" ]; then
			example_location="./is_example.py"
		fi

		python_example=$(curl -X POST "https://api.initialstate.com/api/v1/python/example" -H "X-USER: $username" -H "X-SEC: $password" -H "Accept-Content: text/plain" -m 30 -d "" -s)

		if [ "$python_example" = "INVALID_CREDENTIALS" ]; then
			echo "invalid credentials, let's try that again!"
			download_script
		else
			echo "$python_example" | $SUDO tee "$example_location" > /dev/null
		fi
	else
		echo -n "Enter iot.app.initialstate.com user email: "
		read username < /dev/tty
		echo -n "Enter iot.app.initialstate.com password [input hidden]: "
		read -s password < /dev/tty
		echo ""

		if [ -z "$example_location" ]; then
			example_location="./is_example.py"
		fi

		echo "getting python example script"
		if [ "$INITIALSTATE_AUTH_SVC" != "auth" ]; then
			echo "using $INITIALSTATE_AUTH_SVC"
		fi
		python_example=$(curl -X POST "https://api.init.st/$INITIALSTATE_AUTH_SVC/python/example" -H "X-USER: $username" -H "X-PASS: $password" -H "Accept-Content: text/plain" -m 30 -d "" -s)

		if [ "$python_example" = "INVALID_CREDENTIALS" ]; then
			echo "invalid credentials, let's try that again!"
			download_script
		elif [ "$python_example" = "NOT_CURRENT" ]; then
			echo "your account hasn't been migrated, go to iot.app.initialstate.com to sign in or create a new account"
			download_script
		elif [ "$python_example" = "{\"message\":\"Missing Authentication Token\"}" ]; then
			echo "there's currently an issue with this endpoint, try again later or email support@initialstate.com. Thanks!"
			exit 1
		else
			echo "$python_example" | $SUDO tee "$example_location" > /dev/null
		fi
	fi

}

function download_script_old {
	echo -n "Enter app.initialstate.com user email: "
	read username < /dev/tty
	echo -n "Enter app.initialstate.com password [input hidden]: "
	read -s password < /dev/tty
	echo ""

	if [ -z "$example_location" ]; then
		example_location="./is_example.py"
	fi

	python_example=$(curl -X POST "https://api.initialstate.com/api/v1/python/example" -H "X-USER: $username" -H "X-SEC: $password" -H "Accept-Content: text/plain" -m 30 -d "" -s)

	if [ "$python_example" = "INVALID_CREDENTIALS" ]; then
		echo "invalid credentials, let's try that again!"
		download_script
	else
		echo "$python_example" | $SUDO tee "$example_location" > /dev/null
	fi
}

function setup_first_script {
	echo -n "Do you want automagically get an example script? [y/N] "
	read is_wanted < /dev/tty

	if [ "$is_wanted" = "y" ] || [ "$is_wanted" = "Y" ]; then
		echo "Where do you want to save the example? [default: ./is_example.py]: "
		read example_location < /dev/tty

		if [ "$isstreamer_major_version" -gt "0" ]; then
			download_script
		else
			download_script_old
		fi
	fi

	echo "All done!"
}

check_for_easy_install
check_for_pip
check_for_isstreamer

setup_first_script
