#!/bin/bash

# axyl - the main command wrapper.
# Just reads in the configs, does basic checks, then executes the command.

# Global default config
CONF=/etc/axyl/axyl.conf
if [ -f $CONF ] ; then
  . $CONF
else
  cmderror
fi

# The command
if [ "$1" = "" ] ; then
  axylcmd=help
else
  axylcmd=$1
  shift
fi

function chkroot () {
  if [ $(id -u) != 0 ] ; then
    echo "You must have root privileges to run this command."
  	echo ""
    exit 1
  fi
}

function cmderror () {
  echo "Axyl isn't installed properly - check that $CONF exists and is correct."
  echo ""
  exit 2
}

case $axylcmd in
  # create an Axyl website instance
  create|website|create_website)
    chkroot
    if [ -x ${AXYL_HOME}/install/create-axyl-website.sh ] ; then
      ${AXYL_HOME}/install/create-axyl-website.sh
    else
      cmderror
    fi
    ;;
    
  # remove a website
  remove|remove_website|delete|destroy)
    chkroot
    if [ -x ${AXYL_HOME}/install/remove-axyl-website.sh ] ; then
      ${AXYL_HOME}/install/remove-axyl-website.sh
    else
      cmderror
    fi
    ;;
    
  # install Axyl demo website, if we have it available to us
  demo)
    chkroot
    if [ -x /usr/share/doc/axyl-doc/examples/create-axyl-demo.sh ] ; then
      /usr/share/doc/axyl-doc/examples/create-axyl-demo.sh
    else
      echo "The Axyl demo package isn't available. You need to install the"
      echo "documentation package axyl-doc with 'apt-get axyl-doc'."
      exit 0
    fi
    ;;

  # upgrade all local Axyl databases
  upgrade|dbupgrade)
    if [ -x ${AXYL_HOME}/install/upgrade-axyl-databases.sh ] ; then
      ${AXYL_HOME}/install/upgrade-axyl-databases.sh
    else
      cmderror
    fi
    ;;
    
  # show command help page
  help|--help|-h)
    echo ""
    echo "AXYL COMMANDS"
    echo "All commands are executed by using 'axyl <cmd>'. Commands are:"
    echo ""
    echo " create         - invokes Axyl website creation script"
    echo " remove         - invokes Axyl website removal script"
    echo " upgrade        - upgrades all Axyl website databases"
    echo " demo           - install Axyl demo website if available"
    echo ""
    ;;
    
  *)
    echo "unrecognised command $axylcmd - try 'axyl help' for a valid list of commands"
    exit 0
    ;;
esac

# END