#!/bin/sh
# $Id: extract-account.in,v 1.4 2011/04/14 22:04:17 rhansen Exp $

myname=$(basename "$0") || myname=$0
log() { printf '%s\n' "${myname}: $*"; }
error() { log "ERROR: $*" >&2; }
fatal() { error "$*"; exit 1; }

system=`uname`

case $system in
  FreeBSD)
	systype=bsd
	;;
  NetBSD)
	systype=bsd
	;;
  *)
	systype=unknown
	echo "Unknown system type $system"
	exit 1
	;;
esac

# assume bsd
	
if [ `id -u` != 0 ] ; then
  echo "Must be root."
  exit 2
fi

if [ $# -lt 1 ]; then 
  echo "Usage: extract-account username [username]*"
  exit 3
fi

while [ $# -ge 1 ]; do
  u=$1
  path=`pwd` || fatal "unable to get current working directory"
  tmpdir=skel.$u
  rm -rf "$tmpdir" || fatal "unable to delete ${tmpdir}"
  mkdir $tmpdir || fatal "unable to create ${tmpdir}"
  egrep "^$u:" /etc/master.passwd > $tmpdir/passwd \
      || fatal "account ${u} not found"
  home=`awk -F: '{print $9}' $tmpdir/passwd`
  mkdir $tmpdir/$u || fatal "unable to create ${tmpdir}/${u}"
  mkdir $tmpdir/$u/.ssh || fatal "unable to create ${tmpdir}/${u}/.ssh"
  ak=$home/.ssh/authorized_keys
  if [ -f $ak ]; then
      # use tar instead of 'cp -p' to copy ~/.ssh/authorized_keys in
      # case the uchg flag is set (if uchg flag is set, either 'cp -p'
      # will fail because it can't update atime/mtime, or 'rm -rf
      # $tmpdir' will fail because it can't delete authorized_keys)
      (
          cd "${home}"/.ssh || fatal "unable to cd to ${home}/.ssh"
          tar cf - authorized_keys | (
              cd "${path}"/"${tmpdir}"/"${u}"/.ssh \
                  || fatal "unable to cd to ${path}/${tmpdir}/${u}/.ssh"
              tar xfp - || fatal "unable to copy ${ak}"
          ) || exit 1
      ) || exit 1
  fi
  ef=$home/.extract_files
  if [ -f $ef ]; then
    (
        cd $home || fatal "unable to cd to ${home}"
        tar cfT - $ef | (
            cd $path/$tmpdir/$u || fatal "unable to cd to $path/$tmpdir/$u"
            tar xfp - || fatal "unable to copy files listed in ${ef}"
        ) || exit 1
    ) || exit 1
  fi
  (
      cd $tmpdir || fatal "unable to cd to ${tmpdir}"
      tar cfvz ../$u-skel.tgz . || fatal "unable to create skeleton"
  ) || exit 1
  rm -rf $tmpdir || fatal "unable to clean up ${tmpdir}"
  shift
done
