#!/usr/bin/env bash
set -e

script=$(basename "$0")
version="1.1.1"

help() {
  echo
  echo "$script"
  echo
  echo 'Description: Run jobs from crontab managed by Ansible.'
  echo "Syntax: $script [-n|-i|-V|help]"
  echo "Example: $script -n 'Renew certs for nginx08'"
  echo 'options:'
  echo '  -n    Name of Ansible cron job.'
  echo '  -i    ID of the Ansible cron job.'
  echo "  -V    Show $script version."
  echo "  help  Show $script manual."
  echo
}

if [[ "$1" == 'help' ]]; then
    help
    exit
fi

while getopts ":n: :i: :V" opt; do
  case $opt in
    n) ansible_cron_name=$OPTARG;;
    i) ansible_cron_id=$OPTARG;;
    V) echo "$script version $version"
    exit 0
    ;;
    \?) echo "Invalid option -$OPTARG" >&2
    help
    exit 1;;
  esac
done

if [[ -z "$ansible_cron_name" && -z "$ansible_cron_id" ]]; then
  echo 'Error: You must specify either -n <name> or -i <id>.'
  exit 1
fi

ansible_cron_jobs=$(crontab -l | awk '
  BEGIN { job_num = 1 }
  /^#Ansible: / {
    # Capture the full job name (everything after "#Ansible: ")
    sub(/^#Ansible: /, "", $0);
    name = $0;
    getline;
    print job_num++ "|" name "|" substr($0, index($0, $6));
  }
')

if [[ -n "$ansible_cron_name" ]]; then
  command=$(echo "$ansible_cron_jobs" | awk -F'|' -v name="$ansible_cron_name" '$2 == name { print $3 }')
elif [[ -n "$ansible_cron_id" ]]; then
  command=$(echo "$ansible_cron_jobs" | awk -F'|' -v id="$ansible_cron_id" '$1 == id { print $3 }')
fi

if [[ -z "$command" ]]; then
  echo 'Error: Cron job not found. Maybe try another user?'
  exit 1
fi

echo "Running command: $command"
echo ""
eval "$command"
