#! /bin/bash
USER=$1
IP=$2
hist_dir="/var/log/history"
historyfile="${hist_dir}/${USER}-${IP}-history"

# Only allow expected history paths under /var/log/history
case "$historyfile" in
  "${hist_dir}/"*-history) ;;
  *)
    echo "Input Error: make sure have inputed the right username and IP!"
    exit 1
    ;;
esac

if [ $# != 2 ];then
    echo "=========================================="
    echo "User    IP"
    for fn in /var/log/history/*-history; do
        [ -e "$fn" ] || continue
        [ -L "$fn" ] && continue
        echo "$(basename "$fn")" | awk -F"-" '{print $1 "    "  $2}'
    done
    echo "=========================================="
    echo "Usage:  read-history User IP"
    exit 1
fi

# Reject symlinks (do not follow into arbitrary files)
if [ -L "$historyfile" ] || [ -h "$historyfile" ]; then
    echo "Input Error: make sure have inputed the right username and IP!"
    exit 1
fi
if [ -n "$(readlink "$historyfile" 2>/dev/null)" ]; then
    echo "Input Error: make sure have inputed the right username and IP!"
    exit 1
fi
if [ ! -f "$historyfile" ]; then
    echo "Input Error: make sure have inputed the right username and IP!"
    exit 1
fi

while read -r line
do
  echo "$line" | grep "^#[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]$" &> /dev/null
  if [ "$?" = "0" ];then
    historytime=`date -d "1970-01-01 UTC ${line:1} seconds" "+%F %H:%M:%S"`
    echo -en "$historytime "
  else
    echo -e  "$line"
  fi
done < "$historyfile"
