#!/bin/bash

pp="mobile ALL=(ALL) ALL"
np="mobile ALL=(ALL) NOPASSWD: ALL"

if [ -z $1 ]; then
echo
echo  "Verifying sudoers configuration..."
echo
sv="$(su root -c "grep 'mobile ALL' /etc/sudoers")"
    if [ ! -z "${sv}" ]; then
        su root -c "sed -i '/mobile ALL/d' /etc/sudoers" 2> /dev/null
    fi
    if [ ! -z "${sv}" ]; then
        echo "sudo is already configured for mobile user!"
        echo
        echo "User mobile may run the following commands on ${HOSTNAME}:"
        echo "${sv}"
        su root -c "sed -i '/root ALL/a ${sv}' /etc/sudoers"
        echo
    else
        echo "sudo is not configured for mobile user."
        echo
        echo "Setting up..."
        su root -c "sed -i '/root ALL/a ${np}' /etc/sudoers"
        echo
        echo "User mobile may run the following commands on ${HOSTNAME}:"
        echo "${np}"
        echo
    fi
fi

while getopts 'pn' OPTION; do
  case "$OPTION" in
    p)
      echo "Setting up..."
      su root -c "sed -i '/mobile ALL/d' /etc/sudoers" 2> /dev/null
      su root -c "sed -i '/root ALL/a ${pp}' /etc/sudoers"
      echo
      echo "User mobile may run the following commands on ${HOSTNAME}:"
      echo "${pp}"
      echo
      ;;
    n)
      echo "Setting up..."
      su root -c "sed -i '/mobile ALL/d' /etc/sudoers" 2> /dev/null
      su root -c "sed -i '/root ALL/a ${np}' /etc/sudoers"
      echo
      echo "User mobile may run the following commands on ${HOSTNAME}:"
      echo "${np}"
      echo
      ;;
    ?)
      echo "script usage: sudosetup [-p] [-n]" >&2
      echo
      echo "                  -p : Use password"
      echo "                  -n : No password"
      exit 1
      ;;
  esac
done
shift "$(($OPTIND -1))"
