#!/bin/bash
allow_update_internal_api=false
allow_update_web_app=false
allow_update_console_app=false
for arg in "$@"; do
  echo "Processing: $arg"
  if [[ "$arg" == "internal_api" ]]; then
    echo "internal_api"
    allow_update_internal_api=true 
  elif [[ "$arg" == "web_app" ]]; then
    allow_update_web_app=true
  elif [[ "$arg" == "console_app" ]]; then
    allow_update_console_app=true
  fi
done
WORKING_DIR="/home/pi/test"
rm -rf $WORKING_DIR
mkdir $WORKING_DIR
echo "Directory $WORKING_DIR created!"
if $allow_update_internal_api; then
  systemctl stop internal-api.service
  wget http://files.domcore.pl/configurator/internal-api.tar.gz -P $WORKING_DIR
  echo "internal-api downloaded"
  rm -rf /var/www/internal-api
  tar -xvzf $WORKING_DIR/internal-api.tar.gz -C /var/www/
  echo "internal-api files moved"
  chmod 777 /var/www/internal-api
  chmod +x /var/www/internal-api/Imby.Configurator.InternalAPI.Host
  echo "Added execution access"
  systemctl start internal-api.service
  echo "internal api started"
fi
if $allow_update_web_app; then
  systemctl stop configurator-web-app.service
  wget http://files.domcore.pl/configurator/configurator-web-app.tar.gz -P $WORKING_DIR
  echo "configurator-web-app downloaded"
  rm -rf /var/www/configurator-web-app
  tar -xvzf $WORKING_DIR/configurator-web-app.tar.gz -C /var/www/
  echo "configurator-web-app files moved"
  chmod 777 /var/www/configurator-web-app
  systemctl start configurator-web-app.service
  echo "web app started"
fi
if $allow_update_console_app; then
  systemctl stop edgeConnector
  wget http://files.domcore.pl/edgeConnector.tar.gz -P $WORKING_DIR
  echo "EdgeConnector downloaded"
  rm -rf /usr/sbin/edgeConnector
  tar -xvzf $WORKING_DIR/edgeConnector.tar.gz -C /usr/sbin/
  echo "Files moved"
  chmod +x /usr/sbin/edgeConnector/Imby.EdgeConnector.Presentation.Host
  echo "Added executing access"
  echo "start app"
  systemctl start edgeConnector
fi
rm -rf $WORKING_DIR
