#!/usr/bin/env bash

set -o errexit
set -o nounset

usage(){
  cat <<EOF
This is a one line description of the script.

Usage: template.sh [flags] [<input file>]

Flags:
  -h                      display this help
  -s                      skip the first line (ignore possible header)
  -n                      dry run: do not perform geocoding lookup- just print url

Environment:
  MAPBOX_API_TOKEN        The API token for MapBox

Description: 
  This is a shell script template that reads input from a specified file or STDIN.

EOF
}

INPUT=/dev/stdin  # default input first non-flag arg overides
SKIP=0            # don't skip the first line
MAPBOX_API_TOKEN=${MAPBOX_API_TOKEN:="default_token"}
DRYRUN=0          # make the network request

fail() {
  echo $1 >&2
  exit 1
}

init() {

  OPTIND=1

  while getopts "hsn?" opt; do
      case "$opt" in
      h|\?)
        usage
        exit 0
        ;;
      s)
        SKIP=1
        ;;
      n)
        DRYRUN=1
        ;;
      esac
  done

  shift $((OPTIND-1))
  
  if [[ $# -gt 0 ]]; then
    INPUT=$1
  fi

}

main() {
  # run the init code
  init $*

  # the guts of the script
  while read -r line; do

    # print the line as it exists
    printf "%s" "$line"

    # skip the first line of input
    if [[ $SKIP -eq 1 ]]; then
      SKIP=0
      printf '\n'
      continue
    fi
    
    # if number of fields in the line is greater then 7, then extended address
    # information already exists - just output the line as it exists. 
    if [[ $(echo "$line" | awk -F"\t" '{print NF}') -gt 7 ]]; then
      printf 'This line looks complete!' >2
      printf '\n'
      continue
    fi

    # print the new extended info!
    printf "\t%s\n" "$ext_info"

  done < $INPUT

}

main $*
