#!/bin/bash
set -u

declare Line=
declare Perms=
declare Ownership=
declare File=
declare Cmd=
declare -i ErrorCount=0
declare ThisScript=${0##*/}
declare Version=1.0.3

function msg () { echo -e "$*"; }
function errmsg () { msg "\nError: ${1:-Unknown Error}\n"; ErrorCount+=1; }
function bail () { errmsg "${1:-Unknown Error}"; exit "${2:-1}"; }

msg "Started $ThisScript v$Version as $(id -n -u)@${HOSTNAME%%.*} on $(date)."

while read -r Line; do
   [[ $Line =~ ^[0-9]{3}  ]] || continue
   Perms="${Line%% *}"
   File="${Line##* }"
   Ownership=${Line% *}
   Ownership=${Ownership#* }

   Cmd="chmod $Perms $File"
   msg "Running: $Cmd"
   $Cmd || errmsg "Error running: $Cmd"

   Cmd="chown $Ownership $File"
   msg "Running: $Cmd"
   $Cmd || errmsg "Error running: $Cmd"
done < /root/HostCM/fix_perms.dat

if [[ "$ErrorCount" -eq 0 ]]; then
   msg "\nPermissions updated."
else
   errmsg "$ErrorCount errors encountered updating permissions."
fi

exit "$ErrorCount"
