INPUT_FILE="user.tar"

# This should be changed to your system's jenkins root JENKINS_ROOT="/Users/Shared/Jenkins/Home"
JENKINS_USERS="$JENKINS_ROOT/users"
JENKINS_JOBS="$JENKINS_ROOT/jobs"
JENKINS_CONFIG="$JENKINS_ROOT/config.xml"

# This variable is used so that we can verify that a user is not found
FAIL_TEST=0

importUserPermissions() {
if [ $PERMISSIONS = "true" ]; then
 if [ -f "$1.perm" ]; then
  # delete existing permissions
  sed -i -e "/^.*.*:$1<\/permission>.*/d" $JENKINS_CONFIG
  # Insert new permissions
  while read line; do
   sed -i -e "/^.*<\/authorizationStrategy>.*/ i\\
 $line" $JENKINS_CONFIG
  done < "$1.perm"
 else
  FAIL_TEST=`expr $FAIL_TEST + 1`
 fi
fi
}
importUserFolder() {
if [ -d "$JENKINS_USERS/$1" ] && [ "$REPLACE_CONFIG" = "false" ]; then
 echo "User folder for $1 already exists."
 echo "Enable REPLACE_CONFIG to overwrite existing user folders"
else
 if [ -d "$1" ]; then
  cp -R "./$1" "$JENKINS_USERS/"
 else
  FAIL_TEST=`expr $FAIL_TEST + 1`
 fi
fi
}

importUsers() {
 if [ -d "working" ]; then
  rm -R -f working
 fi
 mkdir working
 cd working

 tar xf "../$INPUT_FILE"
 # Checks if any users have been specified
 if [ ! -z $1 ]; then
  # Iterates over the users if they have
  for u in $*; do
   importUserFolder $u
   importUserPermissions $u
   # if FAIL_TEST is 2, that means both of the above functions failed to find a user
   if [ "$FAIL_TEST" -ge "2" ]; then
    echo "ERROR: User $u is not found!"
    exit 1
   fi
   FAIL_TEST=0
  done
 else
  # Otherwise we import everything!

  # Copies ALL user folders
  for f in `ls -l | awk '/^d.*/{print $(NF);}'`; do
   importUserFolder $f
  done
  for f in `ls *.perm | sed 's/\(.*\)\..*/\1/'`; do
   importUserPermissions $f
  done
 fi

 # Pop up to the workspace
 cd ..

 # post-work cleanup
 rm -R -f working
 rm user.tar
}

importUsers $USERS