#!/bin/bash
DIR_USB=/media/usb_drive/
DIR_OPENSLX=/Openslx/
user_name=`users |  cut -f 1 -d ' '`

function find_path {

  # get the usb_drive's path
  devpath=`readlink -f $usb_drives`
  # check if the usb_drive is mounted
  mount_msg=`mount | grep $devpath`
  # if it is mounted, show the path
  if [[ -n $mount_msg ]]; then
    #echo $mount_msg
    mount_path=`mount | grep $devpath | cut -f 3 -d ' '`
    counter=4
    part_path=`mount | grep $devpath | cut -f 4 -d ' '`
    while [ "$part_path" != "type" ];
      do
        mount_path=$mount_path" "$part_path
        counter=$(($counter+1))
        part_path=`mount | grep $devpath | cut -f $counter -d ' '`
      done
  fi

#  temp_file=$(mktemp)
#  temp_file_name=$(mktemp)
  name=`echo $mount_path | rev | cut -f 1 -d '/'| rev`
  eval echo $mount_path >> /tmp/mount_openslx
  eval echo $name >> /tmp/name_openslx
}



function prepare_usb {

    find_path
    echo $mount_path$DIR_OPENSLX
    # If it is not mounted, mount it
    if [[ ! -n $mount_msg ]]; then
      echo "$devpath não está montado";

      if [ ! -d "$DIR_USB" ]; then
          mkdir /media/usb_drive
        echo "não existe"
      fi
      echo "Montando dispositivo..."
      mount -o uid="$user_name" $devpath /media/usb_drive
      mount_path=/media/usb_drive
    fi
}


function create_dir {
  # crete the dir /Openslx/home
  if [ ! -d "$mount_path$DIR_OPENSLX" ];  then
        echo "oi"
       mkdir "$mount_path"/Openslx/
       mkdir "$mount_path"/Openslx/.config/
       touch "$mount_path"/Openslx/.config/config
       touch "$mount_path"/Openslx/log
  fi
}

function create_user_dir {
  # crete the dir /Openslx/home
  if [ ! -d "$mount_path$new_user$DIR_OPENSLX" ];  then
       mkdir "$mount_path"/Openslx/$new_user
       mkdir "$mount_path"/Openslx/$new_user/Destkop
       mkdir "$mount_path"/Openslx/$new_user/Documents
       mkdir "$mount_path"/Openslx/$new_user/Downloads
       mkdir "$mount_path"/Openslx/$new_user/Music
       mkdir "$mount_path"/Openslx/$new_user/Pictures
       mkdir "$mount_path"/Openslx/$new_user/Public
       mkdir "$mount_path"/Openslx/$new_user/Templates
       mkdir "$mount_path"/Openslx/$new_user/Videos
  fi
}




function read_user_pass {

  #get the username and the password
  new_user=$( dialog --stdout --inputbox 'Digite o nome de usuário:' 0 0 )
  #username should be at linux standards
  while [[ ! $new_user =~ ^[a-z][-a-z0-9]*$ ]]
  do
    new_user=$( dialog --stdout --inputbox 'O nome de usuário consiste apenas de letras, números, hífens(-). E o nome de usuário deve começar apenas com letras. Tente novamente :' 0 0 )
  done
  check_user_name=`  cat "$mount_path"/Openslx/log | grep -w "$new_user"`

  #check if user_name already exists
  while [[  -n $check_user_name ]];
  do
    #get the username and the password
    new_user=$( dialog --stdout --inputbox 'Usuário já existente. Tente novamente:' 0 0 )
    #username should be at linux standards
    while [[ ! $new_user =~ ^[a-z][-a-z0-9]*$ ]]
    do
      new_user=$( dialog --stdout --inputbox 'O nome de usuário consiste apenas de letras, números, hífens(-). E o nome de usuário deve começar apenas com letras. Tente novamente :' 0 0 )
    done
    check_user_name=`cat "$mount_path"/Openslx/log | grep -w "$new_user"`

  done
  pass=$( dialog --stdout --passwordbox 'Por favor, digite a senha:' 0 0 )
  check_pass=$( dialog --stdout --passwordbox 'Por favor, confirme a senha:' 0 0 )

  #check the password
  while [ "$pass" != "$check_pass" ];
  do
    dialog                                            \
       --title 'Erro:'    \
       --msgbox 'As senhas não conferem. Tente novamente.'  \
       6 40
       pass=$( dialog --stdout --passwordbox 'Por favor, digite a senha:' 0 0 )
       check_pass=$( dialog --stdout --passwordbox 'Por favor, confirme a senha:' 0 0 )
  done

  #check if the password
  while [ "$pass" == "" ];
  do
    dialog                                            \
       --title 'Erro:'    \
       --msgbox 'Senha em branco. Tente novamente.'  \
       6 40
       pass=$( dialog --stdout --passwordbox 'Por favor, digite a senha:' 0 0 )
       check_pass=$( dialog --stdout --passwordbox 'Por favor, confirme a senha:' 0 0 )
       #check the password
       while [ "$pass" != "$check_pass" ];
       do
         dialog                                      \
            --title 'Erro:'    \
            --msgbox 'As senhas não conferem. Tente novamente.'  \
            6 40                                            \
            pass=$( dialog --stdout --passwordbox 'Por favor, digite a senha:' 0 0 )
            check_pass=$( dialog --stdout --passwordbox 'Por favor, confirme a senha:' 0 0 )
       done
  done


}

function get_user {

  #get the username and the password
  read_user_pass

  #start the log with a default id
  user_id=$((10000+$(((RANDOM%10000)))))

  check_user_id=`cat "$mount_path"/Openslx/.config/config | grep "SLX_USB_PASSWD" | cut -f 3 -d ':' | grep -w "$user_id"`


  #get the last id
  last_id=`cat "$mount_path"/Openslx/log | cut -f 1 -d ' ' | tail -n1`
  #check if user_id already exists
  while [[  -n $check_user_id ]];
  do
      #user_id will be last id plus one, if it does not exists already
      last_id=$(($last_id+1))
      #check if the last_id already exists in the config file
      check_user_id=`cat "$mount_path"/Openslx/.config/config | grep "SLX_USB_PASSWD" | cut -f 3 -d ':' | grep -w "$last_id"`
      #if is the last_id in the USB DRIVE range, go back to the start of the range
      if [[ ($last_id -ge 19999) && (-n $check_user_id) ]]; then
        last_id=9999
      #otherwise, set user_id
      else
        user_id=$last_id
      fi
  done

}

function success_message {

  #show the confirmation message
  dialog                                            \
     --title 'Cadastro:'    \
     --msgbox 'Cadastro realizado com sucesso.'  \
     6 40

}
function calculate_days_and_pass {
  #get days since Linux Epoch (January 1, 1970)
  seconds=`date +%s`
  minutes=$(($seconds/60))
  hours=$(($minutes/60))
  days=$(($hours/24))
  #encrypt password
  encry_pass=`echo "$pass" | openssl passwd -1 -stdin`
  #echo $encry_pass
}

function create_config {
  #get days since Linux Epoch (January 1, 1970)
  calculate_days_and_pass

  #insert data in the log file
  echo "$user_id $new_user active $date" >> "$mount_path"/Openslx/log


  #insert data in the config file
  echo "SLX_USB_PASSWD=$new_user:x:$user_id:$user_id::/home/$new_user:/bin/bash" >> "$mount_path"/Openslx/.config/config
  echo "SLX_USB_SHADOW=$new_user:$encry_pass:$days:0:99999:7:::" >> "$mount_path"/Openslx/.config/config
  echo "SLX_USB_GROUP=$new_user:x:$user_id;" >> "$mount_path"/Openslx/.config/config

  success_message
}

function create_config_hd {

  calculate_days_and_pass

  #insert data in the log file
  echo "$user_id $new_user active $date" >> "$mount_path"/openslx/log


  #insert data in the config file
  echo "SLX_PASSWD=$new_user:x:$user_id:$user_id::/home/$new_user:/bin/bash" >> "$mount_path"/openslx/config
  echo "SLX_SHADOW=$new_user:$encry_pass:$days:0:99999:7:::" >> "$mount_path"/openslx/config
  echo "SLX_GROUP=$new_user:x:$user_id;" >> "$mount_path"/openslx/config

  success_message
}

function show_menu {
  let i=0 # define counting variable
  W=() # define working array
  while read -r line; do # process file by file
      let i=$i+1
      W+=($i "$line")
  done < <( cat /tmp/name_openslx)
  FILE=$(dialog --title "Selecione o dispositivo para configuração" --menu "OPENSLX" 24 80 17 "${W[@]}" 3>&2 2>&1 1>&3) # show dialog and store output
  clear
  if [ $? -eq 0 ]; then # Exit with OK
    if [[ $FILE != "" ]]
    then
      name_selected=`eval cat /tmp/mount_openslx | head -n$FILE | tail -n1`
      echo $name_selected
    else
      fim_setup
    fi
  fi


}

function fim_setup {
  rm /tmp/mount_openslx
  rm /tmp/name_openslx
  exit
}

function usb_drive {
  touch /tmp/mount_openslx
  touch /tmp/name_openslx
  # list all the usb_drives, mounted or not mounted
  for usb_drives in `ls -l 2>/dev/null /dev/disk/by-id/usb* | rev |  cut -f 3 -d ' ' | rev`; do
  # get only the main devices
     if [[ $usb_drives != *"part"* ]]
     then
        prepare_usb
     fi
  done
  if [[ $usb_drives == "" ]]
    then
    fim_setup
  fi
  show_menu
  mount_path="$name_selected"
  create_dir
  get_user
  create_user_dir
  create_config
  fim_setup
}

function hd_drive {
    # crete the dir /home/openslx and config files

    if [ ! -d "/home/openslx" ];  then
        mkdir -p /home/openslx/
    fi
    if [ ! -e "/home/openslx/config" ]; then
        touch /home/openslx/config
    fi
    if [ ! -e "/home/openslx/log" ]; then
        touch /home/openslx/log
    fi

    read_user_pass


    user_id=cat /etc/passwd | cut -d: -f3 | grep -e 2....$ | sort -h | tail -n 1
    if [ -z "$user_id" ]; then
        user_id=20000
    else
        user_id=$(( $user_id+1 ))
        if [ user_id -ge 30000 ]; then
            echo $0": Provavelmente acabou os id's valido, procurando sequencialmente" >> /home/openslx/log
            #Da para tentar fazer algum código usando diff e {20000..29999}
            #Ai nao precisa desse loop
            for i in $(echo {20000..29999}); do
                user_id=cat /etc/passwd | cut -d: -f3 | grep -e $i$
                if [ -z "$user_id" ]; then
                    user_id=$i
                    break;
                fi
            done
            if [ -z "$user_id" ]; then
                echo $0": Acabou os id's validos" >> /home/openslx/log
                dialog                                            \
                   --title 'Erro:'    \
                   --msgbox 'Estorou o limite de ususario locais nessa maquina, impossivel criar mais'  \
                   6 40
                exit 255
            fi
        fi
    fi

    mount_path="/home"
    create_config_hd

}




id_user=`id -r -u`
if [ $id_user -eq 0 ]; then
    FILE=$(dialog --menu "Que tipo de cadastro você deseja fazer?" 10 50 2 1 "Cadastrar por Pen Drive" 2 "Cadastrar por HD"  3>&2 2>&1 1>&3)
    if [ $FILE -eq 1 ] &> /dev/null;  then
        usb_drive
    elif [ $FILE -eq 2 ] &> /dev/null; then
        hd_drive
    fi
else
    usb_drive
fi
