#!/bin/bash
SSH_PORT=22
args=("$@")

# Обработка опций
for ((i=0; i<$#; i++)); do
  if [ "${args[$i]}" == "-p" ]; then
    SSH_PORT=${args[$i+1]}
    unset 'args[i]'
    unset 'args[i+1]'
  fi
  if [ "${args[$i]}" == "-f" ]; then
    FORCE=1
    unset 'args[i]'
  fi
done

args=("${args[@]}")

SERVER=${args[0]}
PLAYBOOK=${args[1]}
USER=${args[2]}

usage() {
    echo "Usage: run-vps-playbook.sh server playbook [user]"
    echo "server - domain or ip address of the vps server"
    echo "playbook - playbook file"
    echo "[user] - if choose the use it, otherwise used root"
}

if [[ -z "$SERVER" ]]; then
  echo "You must defined SERVER as first argument"
  usage
  exit 1
fi

if [[ -z "$PLAYBOOK" ]]; then
  echo "You must defined PLAYBOOK as second argument"
  usage
  exit 1
fi

if [[ -z "$USER" ]]; then
    USER=root
fi

COMMAND=$(cat <<EOF
ansible-playbook -e "lxc_host=${SERVER}" -e "runner=normal" -e "ansible_user=${USER}" --ssh-common-args="-p $SSH_PORT"
EOF
)

COMMAND="${COMMAND} ${PLAYBOOK}"

if [[ -z "$FORCE" ]]; then
  printf 'Launch ansible playbook:\n%s\n' "${COMMAND}"
  read -p "Are you sure?  " -n 1 -r
  echo    # (optional) move to a new line
  if [[ $REPLY =~ ^[Yyн]$ ]]
  then
      /bin/bash -c "${COMMAND}"
  fi
else
    /bin/bash -c "${COMMAND}"
fi