#!/usr/bin/env bash
#clear
#export PS4='\e[90m+${LINENO} in ${#BASH_SOURCE[@]}>${FUNCNAME[0]}:${BASH_SOURCE[@]##*/} \e[0m'
#set -x

#echo "starting: $0 <LOG_LEVEL=$1>"

### new.method

webitem.usage()
{
  local this=${0##*/}
  echo "You started" 
  echo "$0

  Usage:
  $this: command   Parameter and Description"
  this.help
  echo "

  This programm shall help you to maintain URLs as fils on your operating system.
  Each system uses diffrent Web URL file formats. 
    E.g. macOS uses .webloc files,
         Windows uses .url files,
         Linux uses .desktop files and 
         Web4.x uses .webitem.scenario.json files.
  
  This tool shal hep you to convert each of them into each other.

  Examples
    $this v
    $this init
    ----------
    $this create <url>
    $this webloc2url <weblocFile>
    $this url2webloc <weblocFile>

  "
}

webitem.create() { # <newFileName> <url> # creates a windows url file to the quoted '<url>' named <newFileName>.url
  local newFileName="$1"
  shift
  if [ -z "$newFileName" ]; then err.log "No newFileName given"; return 1; fi

  local url="$1"
  shift
  if [ -z "$url" ]; then err.log "No url given"; return 1; fi

  {
    echo  "[InternetShortcut]"
    echo  "URL=$url" 
  }

  {
    echo  "[InternetShortcut]"
    echo  "URL=$url" 
  } >"$newFileName.url"
}

webitem.webloc2json() { # <weblocFile> # converts a macOS webloc file to a webitem json file
  local weblocFile="$1"
  shift
  if [ -z "$weblocFile" ]; then err.log "No weblocFile given"; return 1; fi

  # local url=$(cat "$weblocFile" | grep -oPm1 "(?<=<string>).*?(?=</string>)")
  # local name=$(basename "$weblocFile" .webloc)
  # local dir=$(dirname "$weblocFile")
  # local jsonFile="$dir/$name.webitem.scenario.json"

  # {
  #   echo  "{"
  #   echo  "  \"name\": \"$name\","
  #   echo  "  \"url\": \"$url\""
  #   echo  "}"
  # } >"$jsonFile"

  plutil -convert json -o - "$weblocFile"

}

webitem.webloc2xml() { # <weblocFile> # converts a macOS webloc file to a webitem xml file
  local weblocFile="$1"
  shift
  if [ -z "$weblocFile" ]; then err.log "No weblocFile given"; return 1; fi


  plutil -convert xml1 -o - "$weblocFile"
}

webitem.webloc2url() { # <weblocFile> <?newFileName> # converts a macOS webloc file to a windows url file
  local weblocFile="$1"
  shift
  if [ -z "$weblocFile" ]; then err.log "No weblocFile given"; return 1; fi

  local newFileName="$1"
  shift
  if [ -z "$newFileName" ]; then 
    local name=$(basename "$weblocFile" .webloc)
    local dir=$(dirname "$weblocFile")
    urlFile="$dir/$name.url"
  else
    urlFile="$newFileName.url"
  fi

  local url=$(plutil -convert xml1 -o - "$weblocFile" | grep -oPm1 "(?<=<string>).*?(?=</string>)")

  {
    echo  "[InternetShortcut]"
    echo  "URL=$url" 
  } >"$urlFile"
}

webitem.start()
{
  #echo "sourcing init"
  source this

  # if [ -z "$1" ]; then
  #   status.discover "$@"
  #   return 0
  # fi

  this.start "$@"
}

webitem.start "$@"

