#!/bin/sh
#
# Quick to do sync only the /etc (most) changed entry to permanent storage.
#
# Rick van der Zwet <rick@wirelessleiden.nl>
#

: ${VERBOSE=false}

usage() {
  cat <<EOF
Usage: $0 [-v] <dryrun|sync>
Options:
  -v     - Verbose diffs
Arguments:
  dryrun - Check the pending changes [default]
  sync   - Sync the pending changes
EOF
  exit ${1:-128}
}

SYNC=false
while [ -n "$1" ]; do
  case "$1" in
    "-v")
      VERBOSE=true; shift
      ;;
    "dryrun")
      SYNC=false; shift
      ;;
    "sync")
      SYNC=true; shift
      ;;
    "-h")
      usage; exit 0;;
    *)
      echo "Invalid Argument -- $1"
      usage
      ;;
   esac
done

# To sync we need to now the content of /cfg
mount -r /cfg || exit 1

# Leave disks in consistent state on exit
trap "umount /cfg; mount -ur /"
trap "exit 1" 1 2 15

$SYNC && mount -uwo noatime / || exit 1
for file in `find /conf/base/etc -type f`; do
  live_file=${file##/conf/base}
  conf_file=/cfg${file##/conf/base/etc}

  # Do not sync files stored on the config mount
  [ -r $conf_file ] && continue
  
  if ! cmp $file $live_file; then
    $VERBOSE && diff $file $live_file
    $SYNC && cp -v $live_file $file
  fi
done

if ! $SYNC; then
  echo "# Dryrun done, commit changes by calling: $0 sync"
fi
