#!/bin/bash

if [ -z "${1}" ]; then
  echo "usage: ${0} [hostname|ipaddr]"
  exit 1
fi

if [[ ${1} =~ ^([0-9]{1,3}\.){3}[0-9]{1,3}$ ]] || \
   [[ ${1} =~ ^([0-9a-f]{0,4}:){2,7}[0-9a-f]{0,4}$ ]]; then
  hostip=${1}
else
  hostip=$(host "${1}" | grep -m 1 address)
  hostip=${hostip##* }
fi

if [[ ${hostip} =~ ^([0-9]{1,3}\.){3}[0-9]{1,3}$ ]] || \
   [[ ${hostip} =~ ^([0-9a-f]{0,4}:){2,7}[0-9a-f]{0,4}$ ]]; then
  hosthw=$(ip neigh show to "${hostip}")
  hosthw=${hosthw#*lladdr }
  hosthw=${hosthw% *}
  if [[ ${hosthw} =~ ^([0-9a-f]{2}:){5}[0-9a-f]{2}$ ]]; then
    wakeonlan "${hosthw}"
  else
    echo "Could not resolve hw address of ${hostip}"
  fi
else
  echo "Could not resolve address of \"${1}\""
fi

