#!/bin/bash
###################################################################### 
#Copyright (C) 2019  Kris Occhipinti
#https://filmsbykris.com

#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, either version 3 of the License, or
#(at your option) any later version.

#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/>.
###################################################################### 

function main(){
  log_dir="$HOME/Documents/$(date +%Y)/maps"
  mkdir -p "$log_dir" || (echo "Failed to create $log_dir";exit 1)
  log="$log_dir/location.csv"

  open="xdg-open"
  echo "Welcome..."
  read -p "Address: " address
  read -p "Place Name: " name
  url="https://nominatim.openstreetmap.org/search?q=$address&format=json&polygon=1&addressdetails=1"
  output="$(wget -qO- "$url"|jq '.[]|.display_name + "|" + .lat + "," + .lon'|head -n 1)"
  echo "$output"

  address="$(echo "$output"|cut -d\| -f1|cut -d\" -f2)"
  gps="$(echo "$output"|cut -d\| -f2|cut -d\" -f1)"
  lat="$(echo "$output"|cut -d\| -f2|cut -d\, -f1|cut -d\" -f1)"
  lon="$(echo "$output"|cut -d\| -f2|cut -d\, -f2|cut -d\" -f1)"
  
  echo "$output"
  osmand="https://osmand.net/go.html?lat=$lat&lon=$lon&z=18"
  echo "$osmand"
  $open "$osmand"
  
  sleep 1
  googlemaps="https://www.google.com/maps/search/$gps/@$gps,17z"
  echo "$googlemaps"
  $open "$googlemaps"

  read -p "Add info?" add
  if [ "$add" = "y" ];then
    echo "Adding $address to $log..."
    echo "$name|$address|$gps|$lat|$lon|$osmand|$googlemaps" >> "$log"
    echo "Good-bye..."
  fi
  exit 0
}

main