#!/bin/sh
# File name: MunkiManifestPicker.command
Version=1.0
# Author: Marion Bates 
# That said, most of these functions and the overall framework of the script were stolen from
# Corey Swertfager's RemoveSymantec.command file that I got so many years ago. Thanks Corey!
#
# Created: March 17, 2016
# Modified: November 7, 2018
#
# Usage: Be admin or root and double-click it
# Summary: See ShowUsage() function.

##############################################################################
# MAKE SURE TO SCROLL TO "START SECTION THAT YOU WILL WANT TO CHECK/CHANGE" 
# AND CHANGE THINGS THERE TO MATCH YOUR ENVIRONMENT OR THIS WILL NOT HELP YOU. 
##############################################################################

# *** Variable Initializations ***

PATH=/bin:/sbin:/usr/bin:/usr/sbin
AbbreviatedScriptName=`basename "$0" .command`
AutoRunScript=TRUE
AutoRunScript=FALSE
FullScriptName=`basename "$0"`
PublicVersion=TRUE
QuitWithoutRestarting=FALSE
$AutoRunScript && QuitWithoutRestarting=TRUE
ShowQuitMessage=TRUE

# *** Function Declarations ***

ShowContents()
{
   # Usage1:    ShowContents [-c] File [TextToShow]
   # Usage2:    ShowContents [-c] -s String [TextToShow]
   # Summary:   Displays contents of File or String. If there are more than
   #            23 lines, more command is used, using TextToShow as the
   #            name of the file; if TextToShow is not passed, "....." is
   #            used. If -c is specified, screen is cleared beforehand. 
   #
   if [ "z$1" = z-c ] ; then
      shift
      clear
   fi  
   if [ "z$1" = z-s ] ; then
      shift
      if [ `printf "%s\n" "$1" | grep -c ""` -gt 23 ] ; then
         ShowContentsCurrentDir=`pwd`
         ShowContentsTempFolder="/private/tmp/$FullScriptName-ShowContents-`date +"%Y%m%d%H%M%S"`"
         mkdir "$ShowContentsTempFolder" 2>/dev/null
         [ ! -d "$ShowContentsTempFolder" ] && return 1
         cd "$ShowContentsTempFolder" 2>/dev/null
         [ "$2" ] && ShowContentsTempFile="$2" || ShowContentsTempFile="....."
         printf "%s\n" "$1" >"$ShowContentsTempFile"
         more -E "$ShowContentsTempFile"
         echo
         cd "$ShowContentsCurrentDir" 2>/dev/null
         rm -rf "$ShowContentsTempFolder" 2>/dev/null
      else
         printf "%s\n" "$1"
      fi
   elif [ -f "$1" ] ; then
      if [ `grep -c "" "$1"` -gt 23 ] ; then
         ShowContentsCurrentDir=`pwd`
         ShowContentsTempFolder="/private/tmp/$FullScriptName-ShowContents-`date +"%Y%m%d%H%M%S"`"
         mkdir "$ShowContentsTempFolder" 2>/dev/null
         [ ! -d "$ShowContentsTempFolder" ] && return 1
         [ "$2" ] && ShowContentsTempFile="$2" || ShowContentsTempFile="....."
         cat "$1" >"$ShowContentsTempFolder/$ShowContentsTempFile"
         cd "$ShowContentsTempFolder" 2>/dev/null
         more -E "$ShowContentsTempFile"
         echo
         cd "$ShowContentsCurrentDir" 2>/dev/null
         rm -rf "$ShowContentsTempFolder" 2>/dev/null
      else
         cat "$1"
      fi
   else
      return 1
   fi
   return 0
}

ShowUsage()
{
   # Usage:     ShowUsage
   # Summary:   Displays script usage message and exits script.
   #
   TEMPFILETEMPLATE="/private/tmp/MunkiManifestPickerTemp"
   TEMPFILE="$TEMPFILETEMPLATE`date +"%Y%m%d%H%M%S"`-1"
   ShowVersion >>"$TEMPFILE"
   $AutoRunScript && echo "
Note:    This script requires no user interaction if run as root." >>"$TEMPFILE"
   echo "

Usage:   Double-click $FullScriptName

Summary: Sets this client's Munki manifest to one of a specified list of options, so as to avoid typos.

Options: -h     Displays help.
         -V     Shows version only.

Examples:
         $FullScriptName

Note:    You must be root or an admin user to run this script. 
         Simply double-click on $FullScriptName and follow the prompts." >>"$TEMPFILE"
   ShowContents "$TEMPFILE"
   /bin/rm "$TEMPFILE"
   ExitScript 0
}

ShowUsageHelp()
{
   # Usage:     ShowUsageHelp [$1]
   # Argument:  $1 = Value with which to exit script (2-255).
   # Summary:   Displays script usage help message and exits script with
   #            value passed to $1 or with 0 if nothing is passed to $1.
   #
   echo
   echo "For help, type:"
   echo
   echo "   $FullScriptName -h"
   echo
   [ -n "$1" ] && exit "$1"
   exit 0
}

ShowVersion()
{
   # Usage:     ShowVersion
   # Summary:   Displays the name and version of script.
   #
   echo "********* $FullScriptName $Version *********"
}

ExitScript()
{
   # Usage:     ExitScript [$1]
   # Argument:  $1 = The value to pass when calling the exit command.
   # Summary:   Checks to see if ShowQuitMessage and RunScriptAsStandAlone
   #            variables are set to TRUE. If so, a message is displayed;
   #            otherwise, no message is displayed. The script is then
   #            exited and passes $1 to exit command. If nothing is passed
   #            to $1, then 0 is passed to exit command. If a non-integer
   #            is passed to $1, then 255 is passed to exit command.
   #
   if [ $ShowQuitMessage = TRUE -a $RunScriptAsStandAlone = TRUE ] ; then
      echo
      echo "NOTE: If you double-clicked this script, quit Terminal application now."
      echo
   fi
   [ -z "$1" ] && exit 0
   [ -z "`expr "$1" / 1 2>/dev/null`" ] && exit 255
   exit $1
}

BeAdmin()
{
   # Usage:     BeAdmin
   # Summary:   Check your privilege.

if [ "`whoami`" != "root" ] ; then   # If not root user,
   if $PublicVersion ; then
      GetAdminPassword TRUE   #    Prompt user for admin password
   else
      ShowVersion
      echo
   fi
   # Run this script again as root
   sudo -p "Please enter your admin password: " "$0" "$@"
   ErrorFromSudoCommand=$?
   # If unable to authenticate
   if [ $ErrorFromSudoCommand -eq 1 ] ; then
      echo "You entered an invalid password or you are not an admin user. Script aborted."
      ExitScript 1
   fi
   if $PublicVersion ; then
      sudo -k   # Make sudo require a password the next time it is run
   fi
   exit $ErrorFromSudoCommand #    Exit so script doesn't run again
fi
}

GetAdminPassword()
{
   # Usage:     GetAdminPassword [$1]
   # Arguments: $1 - Prompt for password. If TRUE is passed, a user that
   #                 is not root will always be asked for a password. If
   #                 something other than TRUE is passed or if nothing is
   #                 passed, then a user that is not root will only be
   #                 prompted for a password if authentication has lapsed.
   # Summary:   Gets an admin user password from the user so that
   #            future sudo commands can be run without a password
   #            prompt. The script is exited with a value of 1 if
   #            the user enters an invalid password or if the user
   #            is not an admin user. If the user is the root user,
   #            then there is no prompt for a password (there is
   #            no need for a password when user is root).
   #            NOTE: Make sure ExitScript function is in the script.
   #
   # If root user, no need to prompt for password
   [ "`whoami`" = "root" ] && return 0
   echo
   # If prompt for password
   if [ "$1" = "TRUE" -o "$1" = "true" ] ; then
      ShowVersion
      echo
      sudo -k   # Make sudo require a password the next time it is run
      echo "You must be an admin user to run this script."
   fi
   # A dummy sudo command to get password
   sudo -p "Please enter your admin password: " date 2>/dev/null 1>&2
   if [ ! $? = 0 ] ; then       # If failed to get password, alert user and exit script
      echo "You entered an invalid password or you are not an admin user. Script aborted."
      ExitScript 1
   fi
}

# *** Beginning of Commands to Execute ***

if [ $# -eq 0 ] ; then   # If no arguments were passed to script
   # Run script as if it was double-clicked in Finder so that
   # screen will be cleared and quit message will be displayed.
   RunScriptAsStandAlone=TRUE
else
   # Run script in command line mode so that
   # screen won't be cleared and quit message won't be displayed.
   RunScriptAsStandAlone=FALSE
fi
if $RunScriptAsStandAlone ; then
   clear 
fi
if [ "z$1" = z-h ] ; then
   ShowUsage
elif [ "z$1" = z-v ] ; then
   echo $Version
   ExitScript 0
fi

BeAdmin
#set -x

######################################################################################
################## START SECTION THAT YOU WILL WANT TO CHECK/CHANGE ##################
######################################################################################

# Path to your munki server
MUNKI_REPO="http://server.example.org"

# Always (re)set the repo in case this is a first-time run.
defaults write /Library/Preferences/ManagedInstalls SoftwareRepoURL "$MUNKI_REPO"

# Always include Apple software updates (which now may be a whole OS! Thanks a lot, Apple.) 
defaults write /Library/Preferences/ManagedInstalls InstallAppleSoftwareUpdates -bool True

# Always (re)set this flag so they can't interrupt an install.
defaults write /Library/Preferences/ManagedInstalls SuppressStopButtonOnInstall -bool True

# Get our current manifest, which will be blank on a first-time run. 
CURRENTMANIFEST=`defaults read /Library/Preferences/ManagedInstalls ClientIdentifier`

# Tell the user what we are now, and offer options to change.
printf "\n\nThe current manifest is: $CURRENTMANIFEST\n\n"
printf "Enter 1 to set it to students (all Macs used by students.)\n"
printf "Enter 2 to set it to faculty (all Macs used by faculty.)\n" 
printf "Enter 3 to set it to sped (all Macs used by SpEd staff.)\n" 
printf "Enter 4 to set it to admins (all Macs used by administrative staff.)\n" 
printf "Enter 5 to set it to tech (Steve blows things up.)\n" 

printf ""
printf "Type in your choice and hit return, please: "
 
read WhatEnteredString
WhatEnteredString=`echo "z$WhatEnteredString" | awk '{print tolower(substr($0,2))}'`

if [ "'$WhatEnteredString" = "'1" -o "'$WhatEnteredString" = "'01" ] ; then
	NEWMANIFEST="students"
elif [ "'$WhatEnteredString" = "'2" -o "'$WhatEnteredString" = "'02" ] ; then
	NEWMANIFEST="faculty"
elif [ "'$WhatEnteredString" = "'3" -o "'$WhatEnteredString" = "'03" ] ; then
	NEWMANIFEST="sped"
elif [ "'$WhatEnteredString" = "'4" -o "'$WhatEnteredString" = "'04" ] ; then
	NEWMANIFEST="admins"
elif [ "'$WhatEnteredString" = "'5" -o "'$WhatEnteredString" = "'05" ] ; then
	NEWMANIFEST="tech"
else
	echo
	echo "Invalid entry; script aborted. Nothing's been changed.\n"
	NEWMANIFEST=$CURRENTMANIFEST
fi

######################################################################################
################### END SECTION THAT YOU WILL WANT TO CHECK/CHANGE ###################
######################################################################################

# Set it and read it back
defaults write /Library/Preferences/ManagedInstalls ClientIdentifier "$NEWMANIFEST"
CURRENTMANIFEST=`defaults read /Library/Preferences/ManagedInstalls ClientIdentifier`

printf "\n\nThe current manifest is: $CURRENTMANIFEST\n\n"
printf "\nIf you want to change it, quit and rerun this script.\n"

ExitScript 0

# *** End of Commands to Execute ***