#!/bin/bash

# NAME: llocate
# PATH: /mnt/e/bin
# DATE: May 22, 2018. Modified July 5, 2020.
# DESC: Use locate command but format output like ll with headings
# PARM: Parameter 1 = locate search string

# UPDT: 2018-07-01 Format date with Time or Previous Year like ls -al.
#       2018-11-09 Filenames trunctated after first space.
#       2020-07-05 Speed up processing. Handle permission denied.

if [[ $# -eq 0 ]]; then
    echo "First parameter must be full or partial file names to search for."
    exit 1
fi

echo "Looking for: $@"

tmpLine=$(locate "$1")

# Was anything found?
if [[ ${#tmpLine} -eq 0 ]] ; then
    echo "No files found. If files created today, did you run 'sudo updatedb' after?"
    exit 1
fi

LastRun=$(stat --printf=%y /var/lib/mlocate/mlocate.db | sed 's/\.[^\n]*//')

# Build output with columns separated by "|" for column command
tmpForm="ACCESS|OWNER|GROUP|SIZE|MODIFIED|NAME (updatdb last ran: $LastRun)"$'\n'

ThisYear=$(date +%Y)

while read -r Line; do

    StatLine=$(stat --printf='%A|%U|%G|%s|%Y|%N\n' "$Line" | sed "s/'//g")

    IFS="|" Arr=($StatLine)
    Seconds="${Arr[4]}"
    [[ $Seconds == "" ]] && continue    # Permission denied

    # Format date with time if it's this year, else use file's year
    if [[ $(date -d @$Seconds +'%Y') == "$ThisYear" ]]; then
        HumanDate=$(date -d @$Seconds +'%b %_d %H:%M')
    else
        HumanDate=$(date -d @$Seconds +'%b %_d  %Y')
    fi

    StatLine="${StatLine/$Seconds/$HumanDate}"
    tmpForm="$tmpForm$StatLine"$'\n'

done <<< "$tmpLine"                           # Read next locate line.

column -t -s '|' <<< "$tmpForm"

exit 0
