#!/bin/bash

#
# This file is part of the Maps-and-Locations (https://github.com/metalx1000/Maps-and-Locations http://FilmsByKris.com).
# Copyright (c) 2022 Kris Occhipinti.
#
# This script creates a log of GPS data for a given image 
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, version 3.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#

if [ "$#" -lt 1 ]
then
  echo "input error"
  echo "example usage: $0 photo.jpg"
  exit 1
fi

thumbs="thumbs"
smallimg="imgs"
log="img.log"

image="$1"
echo -n "$image "


function noGPS(){
  echo "No GPS Found in Image..."
  exit 1
}

exiftool "$image"|grep "GPS Position"||noGPS

basename="$(basename "$image")"
exif="$(exiftool "$image")"
md5="$(md5sum "$image"|awk '{print $1}')"
lat="$(echo "$exif"|grep "GPS Position"|cut -d\: -f2|sed 's/ deg /+(/g'|sed "s/' /\/60)+(/"|sed 's/"/\/3600)/'|awk '{print $1}'|bc -l)"
long="-$(echo "$exif"|grep "GPS Position"|cut -d\, -f2|sed 's/ deg /+(/g'|sed "s/' /\/60)+(/"|sed 's/"/\/3600)/'|awk '{print $1}'|bc -l)"
img_date="$(echo "$exif"|grep "^Date"|head -n1|awk '{print $4}'|tr ":" "/")"
img_time="$(echo "$exif"|grep "^Date"|head -n1|awk '{print $5}')"
epoch="$(date -d "$img_date $img_time" +%s)"

mkdir -p "$thumbs"
mkdir -p "$smallimg"


convert "$image" -resize 128 "$thumbs/$basename"
convert "$image" -resize 512 "$smallimg/$basename"
echo "$md5,$basename,$epoch,$img_date,$img_time,$lat,$long" >> "$log"
