#!/bin/bash
#####################################################################
# GPS Calendar calculator
# This calendar shows dates specific to the GPS community, in which:
# The Week presents the full GPS week number since the 1st epoch (Jan 06, 1980)
# The [Sun-Fri] : [0-6] presents day of week and day of week number
# The [1-31] : [1-366] presents day of month and day of year
#
# https://geodesy.noaa.gov/CORS/resources/gpscals.shtml
#
# History:  
#       Created by: Ming Chen 2023/03/24
#                   ming.chen@noaa.gov
# 
# Usage: source gpsdate.bash
#
#
#####################################################################
valid_date(){
  if [[ $1 =~ ^[0-9]+$ ]]; then
    return 0
  else
    echo "wrong datetime input yyyyddd or yyyymmdd, WWWWD....."
    return 1
  fi
}
gpsw2date(){
  local usg_msg="usage: $0 WWWWD" 
  if [ $# -lt 1 ]; then
    echo "${usg_msg} "
    exit 1
  fi
  valid_date $1
  if [[ $? -ne 0 ]]; then exit ; fi
  local gpsws="${1:0:4}"
  local dow="${1:4:2}"
  
  dds=$(( gpsws * 7 + dow ))

  local mydate=$(date --date="19800106 + $dds days")
  mydate=$(date -d "$mydate" +%Y%m%d)
  echo $mydate
}

date2gpsw(){
  local usg_msg="usage: $0 YYYYMMDD" 
  if [ $# -lt 1 ] && [ ${#1} -ne 8 ] ; then
    echo "${usg_msg} "
    exit 1
  fi
  valid_date $1
  if [[ $? -ne 0 ]]; then exit ; fi
  local mydate="$1"
  d0=$(date -u --date="19800106" +%s)
  d1=$(date -u --date="$mydate" +%s)
  dd=$(( ( d1 - d0  )/(60*60*24) ))
  weeks=$(( dd / 7 ))
  wday=$(( dd % 7 ))
  weeks=$(printf "%04d" $((10#$weeks)))
  echo "$weeks$wday"
}

mkdate(){
  local mydate
  valid_date $1
  if [[ $? -ne 0 ]]; then return 1 ; fi
  if [ ${#1} -eq 8 ]; then
     mydate=`date +%Y%m%d  --date="$1"`
  elif [ ${#1} -eq 7 ]; then
     local jdate="${1:0:4}0101 +$((10#${1:4:3} - 1 ))days"
     mydate=$(date -d "$jdate" +%Y%m%d)
  elif [ ${#1} -eq 5 ]; then
     local gpsw="$1"
     mydate=$(gpsw2date $gpsw)
  else
    echo "wrong datetime input yyyyddd or yyyymmdd....."
    return 1
  fi
  if  [ -n "$2" ]; then
     mydate=$(date -d "$mydate" "+$2")
  fi
  echo $mydate
  return 0
}
#mkdate 21564 "%Y-%m-%d"
