#!/bin/sh

# paste link form clipboard and create a new pet snippet
plink() {
  link=$(xclip -o -sel clipboard)
  desc="$*"
  if [ -z "${desc}" ]; then
   echo "Provide description for link" 
   return 1
  fi

  if [ -z "${link}" ]; then
   echo "Provide url to link" 
   return 1
  fi

  # if [ "$link" =~ ^https?:// ]; then
  if expr "X${link}" : 'X.https?://' >/dev/null; then
    echo "Linking ${link}"
    command_name="xdg-open \\\"${link}\\\""
    description="Link to ${desc}"
    tag="link"

    # Use expect to interact with pet new
    /usr/bin/expect <<EOF
      spawn pet new -t
      expect "Command>"
      send "${command_name}\r"
      expect "Description>"
      send "${description}\r"
      expect "Tag>"
      send "${tag}\r"
      expect eof
EOF
  else
    echo "Not a valid url"
    return 1
  fi
}
