#!/bin/bash

# This file must be executable, otherwise the service cannot run it.

# Run `python_script` while exit code of script is 65.
# At each iteration, pull news from repository and update dependencies.

# Get current directory
this_script_directory=$(cd `dirname $0` && pwd)

# Import variables from my_config.sh
#  `$python_virtual_environment`: python virtual environment directory
#    containing `python` and `pip`
#  `$python_script`: complete path to python script to be run
#  `$pull_from_repository`: boolean
#     if set to true, at each iteration pull from origin
#  `$key`: complete path to private key used to pull
source $this_script_directory/my_config.sh;

# Ensure the success of importing procedure:
## variables of interest should be non-zero (`-z`)
if [ -z "${python_virtual_environment}" ];
then
  printf "Please set in \"my_config.sh\" the path to bot python \
virtual environment\n\
\n\
Example:\n\
python_virtual_environment=\"path/to/virtual/env\"\n\
";
  exit;
fi
if [ -z "${python_script}" ];
then
  printf "Please set in \"my_config.sh\" the path to python script to be run \
\n\
Example:\n\
python_script=\"path/to/python/script.py\"\n\
";
  exit;
elif [ ! -e "${python_script}" ];
then
  printf "File $python_script does not exist\n\
Please point to a valid file.\n\
Example:\n\
python_script=\"path/to/python/script.py\"\n\
";
fi
if [ -z "${key}" ];
then
  printf "Please set in \"my_config.sh\" the path to key\n\
\n\
Example:\n\
key=\"path/to/key.pvt\"\n\
";
  exit;
fi
if [ -z ${pull_from_repository} ];
then
  printf "Please set in \"my_config.sh\" a variable named \
`pull_from_repository`, set to either `true` or `false`.\n\n\
Example:\n\
pull_from_repository=true\n\
";
  exit;
fi

echo "Python script will be run while it exits with value===65.";
i=65;
while [ $i -eq 65 ]
do
if [ $pull_from_repository = true ];
then
  echo "Pulling from remote origin.";
  eval `ssh-agent -s`;
  ssh-add $key;
  git pull;
  eval `ssh-agent -k`;
fi
echo "Updating dependencies";
"$python_virtual_environment/pip" install --upgrade --no-cache-dir \
--no-deps davteutil davtelepot;
echo "Running python script";
"$python_virtual_environment/python" "$python_script";
i=$?;
done