#!/bin/bash

# local variables
YES_ALL="0"
HAVE_USB="0"

DIR_MON="/home/pi/monitoring"
DIR_COMMON="${DIR_MON}/common"
DIR_COMMON_SCRIPTS="${DIR_COMMON}/scripts"
DIR_NODE="${DIR_MON}/node"
DIR_NODE_SCRIPTS="${DIR_NODE}/scripts"
DIR_NODE_BLUELOG="${DIR_NODE}/Bluelog"
DIR_SERVER="${DIR_MON}/server"
DIR_SERVER_SCRIPTS="${DIR_SERVER}/scripts"
DIR_SERVER_WEBUI="${DIR_SERVER_SCRIPTS}/www/html"
DIR_BLUELOG_OUI="/etc/bluelog"
DIR_APACHE="/etc/apache2"
DIR_PHP="/etc/php"
DIR_HTML="/var/www/html"
HTML_USER="www-data"
PI_HOSTNAME="/etc/hostname"
BLUELOG_OUI="oui.txt"
SERVER_DB_MON_USER="mon"

# functions
function print_usage() {
cat <<EOF
Usage:

  node_setup [OPTION]...

Options:

    -c, --common [USB_NAME] [-y]
      Setup device only with common stuff.

    -n, --node [USB_NAME] [-y]
      Setup device as monitoring node.

    -s, --server [USB_NAME] [-y]
      Setup device as monitoring server.

    -a, --all [USB_NAME] [-y]
      Setup device as both monitoring node and server.

    --help
      Print help page.
 
When argument USB_NAME is not specified copying of direcotry tree from USB
will be skipped.
Option -y will disable user prompts (all will be answered 'yes') and will
skip password and hostname setup (to avoid user prompt). However, user prompt
is necessary for MySQL (MariaDB) setup and it will not be skipped!

Examples:

  node_setup -c
  node_setup -n USB_NAME
  node_setup -a USB_NAME -y

EOF
}

function print_help() {
cat <<EOF

COMMON: SETUP MONITORING ENVIRONMENT

This command is used to setup everything needed for monitoring node and server.
To copy directory tree from USB drive name of the USB drive needs to be specified
as argument.

Wi-Fi adapter driver rtl8812au is needed for proper operation of adapter
Alfa AWUS036ACH (used in bachelor thesis) or any other adapter based on
Realtek 8811, 8812, 8814 and 8821 chipsets.

Common setup:
  > copy directory tree from USB (only if USB name specified in argument)
  > set password
  > set hostname
  > change timezone
  > update package-lists
  > upgrade packages (only if package-lists updated)

Node setup:
  > install aircrack-ng
  > install Bluelog
  > generate Bluelog OUI file
  > install rtl8812au driver
  
Server setup:
  > install Apache web server
  > install PHP
  > install MySQL (MariaDB)
  > create MySQL user '${SERVER_DB_MON_USER}'
  > copy web interface to Apache web server

expected directory tree on USB: /media/pi/<USB name>/monitoring/...
local monitoring directory:     ${DIR_MON}
hostname location:              ${PI_HOSTNAME}

Location cannot be altered because scripts on this or remote devices
might be depending on it!

EOF
print_usage
}

function check_git(){
  # first argument - YES_ALL
  # return 0 - continue with git pull
  # return 1 - abort git pull

  git --version &>/dev/null
  if [[ $? != "0" ]];
  then
    if [[ "$1" == "1" ]];
    then
      echo "Installing git..."
      apt-get install git -y
      return 0;
    else
      # user prompt
      while :
      do
        read -p "Git package is needed for this step but has not been found! Do you want to install it? (y/n) " i_git
        case $i_git in
          y|Y|yes|YES)
            echo "Installing git..."
            apt-get install git
            return 0;
            ;;

          n|N|no|NO)
            echo "Package git NOT installed!"
            return 1;
            ;;

          *)
            echo "ERROR: invalid input - expecting y/Y/n/N - try again!"
            ;;

        esac
      done
    fi
  else
    return 0;
  fi

}

function setup_common(){
# return 0 - successfully completed

  echo "======================"
  echo "Starting common setup!"
  echo "======================"

  # local function variables
  goto_upgrade="0";
  new_hostname="raspberrypi";

  ######################################################### copy dir tree from usb
  if [[ "$HAVE_USB" == "1" ]];
  then
    if [[ "$YES_ALL" == "1" ]];
    then
      echo "Copying files from '$DIR_USB_SETUP' to '/home/pi'..."
      cp -r $DIR_USB_SETUP /home/pi
      echo "Changing owner of directory: $DIR_MON to user 'pi'..."
      chown pi:pi $DIR_MON -R
      echo "Making scripts in directory: $DIR_NODE_SCRIPTS executable..."
      chmod +x ${DIR_NODE_SCRIPTS}/*
      echo "Making scripts in directory: $DIR_SERVER_SCRIPTS executable..."
      chmod +x ${DIR_SERVER_SCRIPTS}/*
      echo "Making scripts in directory: $DIR_COMMON_SCRIPTS executable..."
      chmod +x ${DIR_COMMON_SCRIPTS}/*
    else
      # user prompt
      while :
      do
        read -p "Do you want to copy directory tree and scripts from USB drive '${USB_NAME}'? (y/n) " i_copydir
        case $i_copydir in
          y|Y|yes|YES)
            echo "Copying files from $DIR_USB_SETUP to /home/pi"
            cp -r $DIR_USB_SETUP /home/pi
            echo "Changing owner of directory: $DIR_MON to user 'pi'..."
            chown pi:pi $DIR_MON -R
            echo "Making scripts in directory: $DIR_NODE_SCRIPTS executable..."
            chmod +x ${DIR_NODE_SCRIPTS}/*
            echo "Making scripts in directory: $DIR_SERVER_SCRIPTS executable..."
            chmod +x ${DIR_SERVER_SCRIPTS}/*
            echo "Making scripts in directory: $DIR_COMMON_SCRIPTS executable..."
            chmod +x ${DIR_COMMON_SCRIPTS}/*
            break;
            ;;

          n|N|no|NO)
            echo "Direcotry tree and scripts NOT copied!"
            break;
            ;;

          *)
            echo "ERROR: invalid input - expecting y/Y/n/N - try again!"
            ;;

        esac
      done
    fi
  else
    echo "Skipping directory tree copy from USB..."
  fi

  ######################################################### password
  echo "---"
  if [[ "$YES_ALL" == "1" ]];
  then
    echo "Skipping password setup..."
  else
    # user prompt
    while :
    do
      read -p "Do you want to set new password for user 'pi'? (y/n) " i_passwd
      case $i_passwd in
        y|Y|yes|YES)
          sudo -u pi passwd
          break
          ;;

        n|N|no|NO)
          echo "Password NOT changed!"
          break
          ;;

        *)
          echo "ERROR: invalid input - expecting y/Y/n/N - try again!"
          ;;
          
      esac
    done
  fi

  ######################################################### hostname
  echo "---"
  if [[ "$YES_ALL" == "1" ]];
  then
    echo "Skipping hostname setup..."
  else
    # user prompt
    while :
    do
      read -p "Do you want to change hostname? (y/n) " i_hostname
      case $i_hostname in
        y|Y|yes|YES)
          read -p "Enter new hostname (only a-Z, 0-9 and \"-\", case insensitive): " new_hostname
          echo "WARNING: hostname will be changed after reboot!"
          echo "$new_hostname" > $PI_HOSTNAME 
          break;
          ;;

        n|N|no|NO)
          echo "Hostname NOT changed!"
          break;
          ;;

        *)
          echo "ERROR: invalid input - expecting y/Y/n/N - try again!"
          ;;
          
      esac
    done
  fi
  
  ######################################################### timezone
  echo "---"
  if [[ "$YES_ALL" == "1" ]];
  then
    echo "Skipping timezone change..."
  else
    # user prompt
    while :
    do
      read -p "Do you want to list all possible timezones? (y/n) " i_timezone_list
      case $i_timezone_list in
        y|Y|yes|YES)
          timedatectl list-timezones
          break;
          ;;

        n|N|no|NO)
          break;
          ;;

        *)
          echo "ERROR: invalid input - expecting y/Y/n/N - try again!"
          ;;
          
      esac
    done
    while :
    do
      read -p "Do you want to change timezone? (y/n) " i_timezone_change
      case $i_timezone_change in
        y|Y|yes|YES)
          read -p "Enter timezone: " i_timezone
          timedatectl set-timezone $i_timezone
          break;
          ;;

        n|N|no|NO)
          echo "Timezone NOT changed!"
          break;
          ;;

        *)
          echo "ERROR: invalid input - expecting y/Y/n/N - try again!"
          ;;
          
      esac
    done
  fi

  ######################################################### update
  echo "---"
  if [[ "$YES_ALL" == "1" ]];
  then
    echo "Updating package lists..."
    apt-get update -y
    echo "Package lists updated!"
    goto_upgrade="1";
  else
    # user prompt
    while :
    do
      read -p "Do you want to update package lists? (y/n) " i_update
      case $i_update in
        y|Y|yes|YES)
          apt-get update
          echo "Package lists updated!"
          goto_upgrade="1";
          break;
          ;;

        n|N|no|NO)
          echo "Package lists NOT updated!"
          break;
          ;;

        *)
          echo "ERROR: invalid input - expecting y/Y/n/N - try again!"
          ;;

      esac
    done
  fi

  ######################################################### upgrade (only if updated)
  echo "---"
  if [[ "$YES_ALL" == "1" ]];
  then
    echo "Upgrading packages..."
    apt-get upgrade -y
    echo "Packages upgraded!"
  else
    if [ "$goto_upgrade" == "1" ];
    then
      while :
      do
        read -p "Do you want to upgrade packages? (y/n) " i_upgrade
        case $i_upgrade in
          y|Y|yes|YES)
            echo "Upgrading packages..."
            apt-get upgrade
            echo "Packages upgraded!"
            break;
            ;;

          n|N|no|NO)
            echo "Packages NOT upgraded!"
            break;
            ;;

          *)
            echo "ERROR: invalid input - expecting y/Y/n/N - try again!"
            ;;

        esac
      done
    else
      echo "Skipping package upgrade..."
    fi
  fi

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

  return 0

}

function setup_node() {
# return 0 - successfully completed

  echo "===================="
  echo "Starting node setup!"
  echo "===================="
  
  ######################################################### aircrack-ng
  if [[ "$YES_ALL" == "1" ]];
  then
    echo "Installing aircrack-ng..."
    apt-get install aircrack-ng -y
  else
    # user prompt
    while :
    do
      read -p "Do you want to install aircrack-ng? (y/n) " i_aircrack
      case $i_aircrack in
        y|Y|yes|YES)
          apt-get install aircrack-ng
          break;
          ;;

        n|N|no|NO)
          echo "Aircrack-ng installation declined!"
          break;
          ;;

        *)
          echo "ERROR: invalid input - expecting y/Y/n/N - try again!"
          ;;

      esac
    done
  fi

  ######################################################### bluelog
  echo "---"
  # check if $DIR_NODE dir exists
  if [[ -d "$DIR_NODE" ]];
  then
    if [[ "$YES_ALL" == "1" ]];
    then
      echo "Installing Bluelog..."
      check_git "1";
      git_retval=$?;
      if [[ "$git_retval" == "0" ]];
      then
        apt-get install libbluetooth-dev -y
        cd $DIR_NODE
        git clone https://github.com/MS3FGX/Bluelog.git
        cd ${DIR_NODE}/Bluelog
        echo "Patching bluelog.c to change log timestamp to mariaDB friendly format..."
        sed -i 's/strftime(time_string,20,"%D %T",timeinfo);/strftime(time_string,20,"%F %T",timeinfo);/' ./bluelog.c
        sed -i 's/\[%s\]/%s/g' ./bluelog.c
        make
      else
        echo "Cannot install Bluelog - package git is missing!"
      fi
    else
      # user prompt
      while :
      do
        read -p "Do you want to install Bluelog? (y/n) " i_bluelog
        case $i_bluelog in
          y|Y|yes|YES)
            check_git "0";
            git_retval=$?;
            if [[ "$git_retval" == "0" ]];
            then
              apt-get install libbluetooth-dev
              cd $DIR_NODE
              git clone https://github.com/MS3FGX/Bluelog.git
              cd ${DIR_NODE}/Bluelog
              # patch
              echo "Patching bluelog.c to change log timestamp to mariaDB friendly format..."
              sed -i 's/strftime(time_string,20,"%D %T",timeinfo);/strftime(time_string,20,"%F %T",timeinfo);/' ./bluelog.c
              sed -i 's/\[%s\]/%s/g' ./bluelog.c
	            make
            else
              echo "Cannot install Bluelog - package git is missing!"
            fi
            break;
            ;;

          n|N|no|NO)
            echo "Bluelog installation declined!"
            break;
            ;;

          *)
            echo "ERROR: invalid input - expecting y/Y/n/N - try again!"
            ;;

        esac
      done
    fi
  else
    echo "Directory $DIR_NODE does NOT exist: skipping Bluelog installation!"
  fi

  ######################################################### OUI file
  echo "---"
  #check if ${DIR_NODE_BLUELOG} exists
  if [[ -d "${DIR_NODE_BLUELOG}" ]];
  then

    if [[ "$YES_ALL" == "1" ]];
    then
      # check if oui.tmp exists
      if [[ -f "/tmp/${BLUELOG_OUI}" ]];
      then
        echo "Removing existing OUI tmp file..."
        rm /tmp/${BLUELOG_OUI}
      fi
     
      # create dir /etc/bluelog if it does not exist
      mkdir -p ${DIR_BLUELOG_OUI}
      cd ${DIR_BLUELOG_OUI}
      echo "Starting bluelog gen_oui script..."
      ${DIR_NODE_BLUELOG}/scripts/gen_oui.sh check
    else
      # user prompt
      while :
      do
        read -p "Do you want to generate OUI file for Bluelog? (y/n) " i_bluelog_oui
        case $i_bluelog_oui in
          y|Y|yes|YES)
            chmod +x ${DIR_NODE_BLUELOG}/scripts/gen_oui.sh
            # create dir /etc/bluelog if it does not exist
            mkdir -p ${DIR_BLUELOG_OUI}
            cd ${DIR_BLUELOG_OUI}
            echo "Starting bluelog gen_oui script..."
            ${DIR_NODE_BLUELOG}/scripts/gen_oui.sh force
            break;
            ;;

          n|N|no|NO)
            echo "Bluelog OUI file generation declined!"
            break;
            ;;

          *)
            echo "ERROR: invalid input - expecting y/Y/n/N - try again!"
            ;;

        esac
      done
    fi
    
  else
    echo "WARNING: Bluelog not installed: skipping OUI file generation!"
  fi

  ######################################################### rtl8812au driver
  echo "---"
  if [[ "$YES_ALL" == "1" ]];
  then
    echo "Installing DKMS (needed to install rtl8812au driver)..."
    apt-get install dkms -y
    cd $DIR_MON
    echo "Cloning rtl8812au repository from Github..."
    check_git "1";
    git_retval=$?;
    if [[ "$git_retval" == "0" ]];
    then
      git clone -b "v5.3.4" https://github.com/aircrack-ng/rtl8812au.git
      cd rtl8812au
      echo "Executing rtl18812au installation script..."
      ./dkms-install.sh
    else
      echo "Cannot install rtl18812au driver - package git is missing!"
    fi
  else
    # user prompt
    while :
    do
      read -p "Do you want to install rtl8812au driver? (y/n) " i_driver
      case $i_driver in
        y|Y|yes|YES)
          apt-get install dkms
          cd $DIR_MON
          echo "Cloning rtl8812au repository from Github..."
          check_git "0";
          git_retval=$?;
          if [[ "$git_retval" == "0" ]];
          then
            git clone -b "v5.3.4" https://github.com/aircrack-ng/rtl8812au.git
            cd rtl8812au
            echo "Executing rtl18812au installation script..."
            ./dkms-install.sh
          else
            echo "Cannot install rtl18812au driver - package git is missing!"
          fi
          break;
          ;;

        n|N|no|NO)
          echo "Driver rtl8812au installation declined!"
          break;
          ;;

        *)
          echo "ERROR: invalid input - expecting y/Y/n/N - try again!"
          ;;

      esac
    done
  fi

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

  return 0
}

function setup_server() {
# return 0 - successfully completed

  echo "======================"
  echo "Starting server setup!"
  echo "======================"
  
  ######################################################### Apache
  if [[ "$YES_ALL" == "1" ]];
  then
    echo "Installing Apache (web server)..."
    apt-get install apache2 -y
  else
    # user prompt
    while :
    do
      read -p "Do you want to install Apache (web server)? (y/n) " i_apache
      case $i_apache in
        y|Y|yes|YES)
          echo "Installing Apache..."
          apt-get install apache2
          break;
          ;;

        n|N|no|NO)
          echo "Apache (web server) installation declined!"
          break;
          ;;

        *)
          echo "ERROR: invalid input - expecting y/Y/n/N - try again!"
          ;;

      esac
    done
  fi

  ######################################################### PHP (only if Apache installed)
  echo "---"
  if [ -d "${DIR_APACHE}" ];
  then

    if [[ "$YES_ALL" == "1" ]];
    then
      echo "Installing PHP with recommended modules..."
      apt install php7.3 php7.3-mbstring php7.3-mysql php7.3-curl php7.3-gd php7.3-zip -y
    else
      while :
      do
        read -p "Do you want to install PHP? (y/n) " i_php
        case $i_php in
          y|Y|yes|YES)
            echo "Installing PHP with recommended modules..."
            apt install php7.3 php7.3-mbstring php7.3-mysql php7.3-curl php7.3-gd php7.3-zip
            break;
            ;;

          n|N|no|NO)
            echo "PHP installation declined!"
            break;
            ;;

          *)
            echo "ERROR: invalid input - expecting y/Y/n/N - try again!"
            ;;

        esac
      done
    fi

  else
    echo "WARNING: Apache NOT installed: skipping PHP installation!"
  fi

  ######################################################### mysql
  echo "---"
  if [[ "$YES_ALL" == "1" ]];
  then
    echo "Installing MySQL database (MariaDB)..."
    apt-get install mariadb-server -y
    echo "Installing PHP-MySQL connector module"
    apt-get install php-mysql -y
    echo "Starting MySQL secure installation..."
    mysql_secure_installation
  else
    # user prompt
    while :
    do
      read -p "Do you want to install MySQL database (MariaDB)? (y/n) " i_mysql
      case $i_mysql in
        y|Y|yes|YES)
          echo "Installing MySQL database (MariaDB)..."
          apt-get install mariadb-server
          echo "Installing PHP-MySQL connector module"
          apt-get install php-mysql
          echo "Starting MySQL secure installation..."
          mysql_secure_installation
          break;
          ;;

        n|N|no|NO)
          echo "MySQL database (MariaDB) installation declined!"
          break;
          ;;

        *)
          echo "ERROR: invalid input - expecting y/Y/n/N - try again!"
          ;;

      esac
    done
  fi

  ######################################################### mysql mon user
  echo "---"
  if [[ "$YES_ALL" == "1" ]];
  then

    echo "Creating new MySQL user '${SERVER_DB_MON_USER}'..."

    # root password prompt
    read -s -p "Enter root MySQL password (set in previous step): " i_root_usr_pass
    echo ""
    
    # NEW mon password prompt
    while :
    do
      read -s -p "Enter password for new MySQL user '${SERVER_DB_MON_USER}': " i_mon_usr_pass_1
      echo ""
      read -s -p "Enter the password again: " i_mon_usr_pass_2
      echo ""
      if [[ "$i_mon_usr_pass_1" == "$i_mon_usr_pass_2" ]]
      then
        echo "Passwords match!"
        break;
      else
        echo "Passwords do NOT match - try again!"
      fi
    done
    
    # query - create mon user
    mysql -u root -p"${i_root_usr_pass}" <<EOF
CREATE USER '${SERVER_DB_MON_USER}'@'localhost' IDENTIFIED BY '${i_mon_usr_pass_1}';
EOF
    # check exit code of create user mon mysql query
    if [ $? -eq 0 ];
    then
      # when success grant FILE privileges
      echo "MySQL: user '${SERVER_DB_MON_USER}' created successfully!"
      echo "MySQL: granting privileges to user '${SERVER_DB_MON_USER}'"
      mysql -u root -p"${i_root_usr_pass}" <<EOF
GRANT FILE ON *.* TO '${SERVER_DB_MON_USER}'@'localhost';
EOF
      # check exit code of grant FILE privileges query
      if [ $? -eq 0 ];
      then
        # when success flush privileges
        echo "MySQL: privileges granted successfully!"
        echo "MySQL: reloading privileges..."
        mysql -u root -p"${i_root_usr_pass}" <<EOF
FLUSH PRIVILEGES;
EOF
      else
        # when failed remove mon user
        echo "ERROR MySQL: query to grant privileges to user '${SERVER_DB_MON_USER}' failed!"
        echo "MySQL: removing user '${SERVER_DB_MON_USER}'"
    mysql -u root -p"${i_root_usr_pass}" <<EOF
DROP USER '${SERVER_DB_MON_USER}'@'localhost';
EOF
      fi
    else
      # when failed to create user
      echo "ERROR MySQL: query to create user '${SERVER_DB_MON_USER}' failed!"
    fi

  else
    # user prompt
    while :
    do
      read -p "Do you want to create new MySQL user '${SERVER_DB_MON_USER}' (y/n) " i_mysql_usr
      case $i_mysql_usr in
        y|Y|yes|YES)

          # root password prompt
          read -s -p "Enter root MySQL password (set in previous step): " i_root_usr_pass
          echo ""
    
          # NEW mon password prompt
          while :
          do
            read -s -p "Enter password for new MySQL user '${SERVER_DB_MON_USER}': " i_mon_usr_pass_1
            echo ""
            read -s -p "Enter the password again: " i_mon_usr_pass_2
            echo ""
            if [[ "$i_mon_usr_pass_1" == "$i_mon_usr_pass_2" ]]
            then
              echo "Passwords match!"
              break;
            else
              echo "Passwords do NOT match - try again!"
            fi
          done
    
          # query - create mon user
          mysql -u root -p"${i_root_usr_pass}" <<EOF
CREATE USER '${SERVER_DB_MON_USER}'@'localhost' IDENTIFIED BY '${i_mon_usr_pass_1}';
EOF
          # check exit code of create user mon mysql query
          if [ $? -eq 0 ];
          then
            # when success grant FILE privileges
            echo "MySQL: user '${SERVER_DB_MON_USER}' created successfully!"
            echo "MySQL: granting privileges to user '${SERVER_DB_MON_USER}'"
            mysql -u root -p"${i_root_usr_pass}" <<EOF
GRANT FILE ON *.* TO '${SERVER_DB_MON_USER}'@'localhost';
EOF
            # check exit code of grant FILE privileges query
            if [ $? -eq 0 ];
            then
              # when success flush privileges
              echo "MySQL: privileges granted successfully!"
              echo "MySQL: reloading privileges..."
              mysql -u root -p"${i_root_usr_pass}" <<EOF
FLUSH PRIVILEGES;
EOF
            else
              # when failed remove mon user
              echo "ERROR MySQL: query to grant privileges to user '${SERVER_DB_MON_USER}' failed!"
              echo "MySQL: removing user '${SERVER_DB_MON_USER}'"
          mysql -u root -p"${i_root_usr_pass}" <<EOF
DROP USER '${SERVER_DB_MON_USER}'@'localhost';
EOF
            fi
          else
            # when failed to create user
            echo "ERROR MySQL: query to create user '${SERVER_DB_MON_USER}' failed!"
          fi
          break;
          ;;

        n|N|no|NO)
          echo "MySQL database '${SERVER_DB_MON_USER}' user creation declined!"
          break;
          ;;

        *)
          echo "ERROR: invalid input - expecting y/Y/n/N - try again!"
          ;;

      esac
    done
  fi

  ######################################################### www copy (only if Apache & PHP installed)
  echo "---"
  if [ -d "${DIR_PHP}" ];
  then

    if [[ "$YES_ALL" == "1" ]];
    then
      echo "Removing old web interface from Apache web server..."
      rm -r ${DIR_HTML}/*
      echo "Copying monitoring web interface to Apache web server..."
      cp -r ${DIR_SERVER_WEBUI}/* ${DIR_HTML}
      echo "Changing owner of ${DIR_HTML} to Apache web server (${HTML_USER})..."
      chown -R ${HTML_USER} ${DIR_HTML}
    else
      while :
      do
        read -p "Do you want to copy web interface to Apache web server? (y/n) " i_www_copy
        case $i_www_copy in
          y|Y|yes|YES)
            echo "Removing old web interface from Apache web server..."
            rm -r ${DIR_HTML}/*
            echo "Copying monitoring web interface to Apache web server..."
            cp -r ${DIR_SERVER_WEBUI}/* ${DIR_HTML}
            echo "Changing owner of ${DIR_HTML} to Apache web server (${HTML_USER})..."
            chown -R ${HTML_USER} ${DIR_HTML}
            break;
            ;;

          n|N|no|NO)
            echo "Copying of web interface to Apache web server declined!"
            break;
            ;;

          *)
            echo "ERROR: invalid input - expecting y/Y/n/N - try again!"
            ;;

        esac
      done
    fi

  else
    echo "WARNING: Apache and/or PHP NOT installed: skipping copying of web interface to Apache web server!"
  fi

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

  return 0
}

function parse_args() {
# return 0 - successfully completed
# first  argument - 1st arg
# second argument - 2nd arg

# format:
#   common_setup {option} [USB_NAME] [-y]

  # parse 1st arg
  case $1 in
    "")
      # setup without USB
      echo "Starting setup without USB!"
      ;;
    -y|--yes)
      # setup without USB, yes to all
      YES_ALL="1";
      echo "Starting setup without USB!"
      echo "User prompts disabled!"
      ;;
    *)
      # setup with USB, check 2nd argument
      HAVE_USB="1";
      USB_NAME="$1";
      echo "USB name set to: '${1}'!"
      DIR_USB_SETUP="/media/pi/${USB_NAME}/monitoring"
      echo "USB setup path set to '${DIR_USB_SETUP}'!"
      ;;
  esac

  # parse 2nd arg
  case $2 in
    "")
      # 2nd argument empty
      ;;
    -y|--yes)
      # setup with USB, yes to all
      YES_ALL="1";
      echo "User prompts disabled!"
      ;;
    *)
      echo "ERROR: second argument $2 unknown!"
      print_usage
      exit 1
      ;;
  esac

}

# options parsing

if [[ $# -eq 0 ]];
then
  echo ""
  print_usage
  exit 1
fi


case $1 in
  --help)
    print_help
    exit 0
    ;;

  -c|--common)
    parse_args $2 $3
    setup_common
    ;;

  -n|--node)
    parse_args $2 $3
    setup_common
    setup_node
    ;;

  -s|--server)
    parse_args $2 $3
    setup_common
    setup_server
    ;;

  -a|--all)
    parse_args $2 $3
    setup_common
    setup_node
    setup_server
    ;;

  *)
    echo "ERROR: option $1 unknown!"
    print_usage
    exit 1
    break
    ;;
esac
