#!/bin/ash
#
# dedup_passwd:
# This script removes all duplicate user records from the /etc/passwd file.
# It is typically run as part of the post install process. If no options are
# used, input and output files will default to /etc/passwd
#
# Usage:
# dedup-passwd [-i INPUT_FILE] [-o OUTPUT_FILE]

# Default values
INFILE=/etc/passwd
OUTFILE=/etc/passwd

# Process arguments
if [[ "$1" == "-i" && ! "$2" == "" ]]
  then
  INFILE=$2; shift; shift;
fi
if [[ "$1" == "-o" && ! "$2" == "" ]]
  then
  OUTFILE=$2; shift; shift;
fi
if [[ "$1" == "-i" && ! "$2" == "" ]]
  then
  INFILE=$2; shift; shift;
fi
if [ ! "$1" == "" ]
  then
  # Unknown or excess arguments
  echo "Usage:"
  echo "dedup-passwd [-i INPUT_FILE] [-o OUTPUT_FILE]"
  exit
fi

if [ -z "`sed -e 's/:.*//' -e 's/ *#.*//' $INFILE | uniq -d`" -a -z "grep '[^[:print:]]'" ]; then
  # No duplicates found, no invalid characters, nothing to do
  exit
fi

# Replace the first entry for a user with the last entry for that user.
# All other entries will be removed. Lines which do not contain a user
# entry will not me modified.
cat $INFILE | grep -v "[^[:print:]]" | awk -F : '{
        if (substr($1, 1, 1) == "#")
            out[lines++]=$0
        else {
            if (entry[$1] == 0)
                out[lines++]= "@" $1
            entry[$1] = $0
        }
    }
    END {
        for (i=0; i<lines; i++) {
            out_line=out[i]
            if(substr(out_line, 1, 1) == "@")
                print entry[substr(out_line, 2)]
            else
                print out_line
        }
 }' > /tmp/passwd.dedup

mv -f /tmp/passwd.dedup $OUTFILE 2>/dev/null
