#!/bin/bash
# 7.4.2017 Stefan Abeln script creation
# 13.4.2017 Add optional creation of new user
# Script restores backup of home directory of student user

# Check if an additional argument was supplied
if [ $# -eq 0 ]
 then
   # Just restore student user
   cd /home
   echo "This script will erase the existing directory of the user student and restore a previously made backup. This will delete all data of user student being stored since delivery. So please backup data before running this script!"
   read -p "Do you want to proceed? If so please press any (yes/Yes/YES). Any other entry will stop this script. To proceed enter any --> yes or Yes or YES <--  " ANSWER

   UANSWER=`echo $ANSWER | awk '{print toupper($0)}'`

   case $UANSWER in
    YES)
           echo "Restore will now start"
           ;;
    *)
           echo "You did not answer with (yes/Yes/YES)."
           echo "Script will be aborted"
           exit
           ;;
   esac

   echo "Erasing old directory"
   sudo rm -rf /home/student
   sudo mkdir /home/student
   sudo chown student:labdoo /home/student
   cd /home/student
   echo "Restoring backup"
   sudo tar xvzf /root/backup_student.tgz .
   echo "Finished restoring."
 else
   # Create new user if previous backup from user student is present
   echo "If a backup from student user is present and provided username does not yet exist on this machine it will be created."
   if sudo file /root/backup_student.tgz 2>&1 >/dev/null
    then
      # Backup file is present, new user can be created if not already existing.
      if id "$1" >/dev/null 2>&1
       then
         echo "User $2 already exists on this machine."
         echo "Exiting now"
         exit
        else
          # Creating new user
          sudo useradd -d /home/$1 -g labdoo -M $1
          sudo mkdir /home/$1
          cd /home/$1
          sudo tar xvfz /root/backup_student.tgz .
          sudo chown --recursive $1:labdoo .
          # Set password for new user
          sudo passwd $1
      fi
  fi
fi
