#!/bin/sh
#
# linbo_patch_registry
# thomas@linuxmuster.net
# 20230726
#

usage(){
  local RC="$1"
  echo
  echo "Patches windows registry."
  echo
  echo "Usage:"
  echo "  linbo_patch_registry <regfile> [windowspartition] | [help]"
  echo
  echo "It is assumed that the windows partition is mounted under /mnt or"
  echo "specified as the second parameter."
  echo
  exit "$RC"
}


# print help
[ -z "$1" -o "$1" = "help" ] && usage 0

# get environment
source /usr/share/linbo/shell_functions
echo "### $timestamp $(basename "$0") $@ ###"

# registryfile to process
regfile="$1"
[ -s "$regfile" ] || usage 1
regtmp="/tmp/$(basename "$regfile")"
mntpnt="/mnt"

# check specified partition
if [ -n "$2" ]; then
  [ -b "$2" ] || usage 1
  if ! ismounted "$2" /mnt rw; then
    mntpnt="/tmp/mnt"
    linbo_mount "$2" "$mntpnt" || usage 1
    mounted="yes"
  fi
fi

# hive directory
hive_dir="$mntpnt/Windows/System32/config"
if [ ! -d "$hive_dir" ]; then
  echo "$hive_dir does not exist!"
  [ -n "$mounted" ] && umount "$mntpnt"
  exit 1
fi

# registry file header
header="Windows Registry Editor Version 5.00"

# prefix for the created regfiles
prefix="/tmp/reg.$$."

# replace template with hostname & repair case of registry paths
cp "$regfile" "$regtmp"
sed -i 's|{\$HostName\$}|'"$HOSTNAME"'|g
        s|@@hostname@@|'"$HOSTNAME"'|g
        s|\\currentcontrolset\\|\\ControlSet001\\|Ig' "$regtmp"

# split regfile into handy parts
grep ^"[\[\"]" "$regtmp" | csplit -s -z -f "$prefix" - '/^\[/' '{*}'

# iterate over regfiles
for i in ${prefix}*; do
  # add windows registry header
  sed -i "1s/^/$header\n\n/" "$i"
  branch="$(grep -i ^'\[HKEY' "$i" | awk -F \\\\ '{print $1}' | awk -F \[ '{print $2}')"
  hive="$(grep -i ^'\[HKEY' "$i" | awk -F \\\\ '{print $2}')"
  hive_file="$hive_dir/$(echo "$hive" | tr a-z A-Z)"
  if [ ! -s "$hive_file" ]; then
    echo "Skipping invalid hive $(grep -i ^'\[HKEY' "$i")."
    continue
  fi
  reged -I -C "$hive_file" "$branch\\$hive" "$i"
done

[ -n "$mounted" ] && umount "$mntpnt"

exit "$?"
