#!/bin/bash
#
# Copyright 2014 Red Hat, Inc.
#
# NAME
#     lab-phpdb - grading script for RH254/RH299 PHP + MariaDB Exercise
#
# SYNOPSIS
#     lab-phpdb {setup|grade}
#
#        setup - perform configuration adjustments to the system
#        grade - perform evaluation steps to the system
#
#     The setup function needs to be run on server
#     The grade function needs to be run on desktop
#
# DESCRIPTION
#     This script, based on singular argument, either does setup or
#     grading for the particular lab
#
# CHANGELOG
#   * Mon May 26 2014 Wander Boessenkool <wboessen@redhat.com>
#   - Initial version

PATH=/usr/bin:/bin:/usr/sbin:/sbin

# Initialize and set some variables
MYHOST=""
CMD=""
DEBUG='true'
RUN_AS_ROOT='true'

# Source library of functions
source /usr/local/bin/labtool.shlib
trap on_exit EXIT

# Additional functions for this shell script
function print_usage {
  local problem_name=$(basename $0 | sed -e 's/^lab-//')
  cat << EOF
This script controls the setup and grading of this lab.
Usage: lab ${problem_name} COMMAND
       lab ${problem_name} -h|--help
COMMAND is one of:
    setup - perform any setup steps for this lab on this machine
    grade - perform any grading steps and report on this machine
EOF
}


function install_packages {
  echo -n "Installing Packages...  "
  yum -y install httpd mariadb-server &> /dev/null
  print_SUCCESS
  echo -n "Starting and enabling services...  "
  systemctl enable httpd.service mariadb.service &> /dev/null
  systemctl restart httpd.service mariadb.service &> /dev/null
  print_SUCCESS
}

function seed_db {
  echo -n "Creating and seeding DB...  "
  # Cleanup old cruft, students might attempt tomrun this twice and
  # expect results...
  mysql <<< "DROP DATABASE mtg;" &> /dev/null
  mysql <<< "DROP USER 'tim'@'localhost';" &> /dev/null
  mysql << 'EOF'
CREATE DATABASE IF NOT EXISTS mtg;
CREATE USER 'tim'@'localhost' IDENTIFIED BY 'fireball';
GRANT ALL PRIVILEGES ON mtg . * TO 'tim'@'localhost';
USE mtg;
CREATE TABLE Cards
(
  CardID INT NOT NULL AUTO_INCREMENT,
  Name VARCHAR(255) NOT NULL,
  Cost VARCHAR(255) NOT NULL,
  PRIMARY KEY (CardId)
);
INSERT INTO Cards VALUES (NULL, "MoxMoxMox", "1");
INSERT INTO Cards VALUES (NULL, "Blackest Lotus", "0");
INSERT INTO Cards VALUES (NULL, "Gryll Bears", "2{G}{G}");
INSERT INTO Cards VALUES (NULL, "Prodigal Open Sourcerer", "1{U}");
EOF
  RESULT=$?
  if [ ! "${RESULT}" -eq 0 ]; then
    print_FAIL
    echo " - Error while creating and seeding database"
    exit 1
  fi
  print_SUCCESS
}


function drop_app_varwwwhtml {
  echo -n "Creating PHP application in /var/www/html...  "
  cat > /var/www/html/index.php << 'EOF'
<html>
  <head>
    <title>Tim's Card DB</title>
  </head>
  <body>
    <?php
    $dbhost = 'localhost';
    $dbuser = 'tim';
    $dbpass = 'fireball';
    $dbdb = 'mtg';
    $conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbdb);
    if (! $conn) {
      die('Unable to connect to database:' . mysql_error());
    }
    echo '<div>Connected to Database</div>';
    $contents = mysqli_query($conn, "SELECT * from Cards");
    echo "<table><tr><th>ID</th><th>Name</th><th>Cost</th></tr>";
    while ($row = mysqli_fetch_array($contents)) {
      echo "<tr><td>" . $row['CardID'] . "</td><td>" . $row['Name'];
      echo "</td><td>" . $row['Cost'] . "</td></tr>";
    }
    echo "</table>";
    ?>
  </body>
</html>
EOF
  print_SUCCESS
}

function lab_setup {
  VMNAME=$1
  case $VMNAME in
    desktop)
      print_FAIL && echo "The setup script needs to be run on server"
      ;;
    server)
      install_packages
      seed_db
      drop_app_varwwwhtml
      ;;
    *)
      # Should never get here, but what the hey....
      print_FAIL && echo "The setup script needs to be run on desktop"
      ;;
  esac
}

function lab_grade {
  VMNAME=$1
  case $VMNAME in
    desktop)
      echo -n "Checking for correct response...  "
      if ! curl http://server${X}.example.com 2>/dev/null | grep -q '<td>Prodigal Open Sourcerer' &> /dev/null ; then
        print_FAIL
        echo "Could not connect to http://server${X}.example.com, or wrong content returned."
      else
        print_SUCCESS
      fi
      ;;
    server)
      # Obviously adjust this to actual commands if script needs
      # to run on server - and adjust the catchall message with *)
      print_FAIL && echo "The grade script needs to be run on desktop"
      ;;
    *)
      # Should never get here, but what the hey....
      print_FAIL && echo "The grade script needs to be run on desktop"
      ;;
  esac
}

# Main area

# Check if to be run as root (must do this first)
if [[ "${RUN_AS_ROOT}" == 'true' ]] && [[ "${EUID}" -gt "0" ]] ; then
  if [[ -x /usr/bin/sudo ]] ; then
    ${SUDO:-sudo} $0 "$@"
    exit
  else
    # Fail out if not running as root
    check_root
  fi
fi

# Process command line
# Parse input
case $1 in
  setup|grade)
    CMD=$1
    ;;
  -h|--help)
    print_usage
    exit 0
    ;;
  *)
    echo Bad option $1
    print_usage
    exit 1
    ;;
esac
# Validation
[[ -z "$CMD" ]] && debug "Missing command" && print_usage && exit 1

# Get local system information
get_X

# Branch based on short (without number) hostname
case $MYHOST in
  desktop|server)
    lab_$CMD $MYHOST
    ;;
  *)
    debug "Bad or missing hostname - $MYHOST"
    debug "This command needs to be run on desktop or server"
    exit 3
    ;;
esac
