<?php

// if running this from https://cgi.stanford.edu/~sunetid/cgi-bin/
// or otherwise using an stunnel connection
// $host="127.0.0.1";

// if not using a stunnel connection then use this $host
// definition
$host="mysql-app.stanford.edu";

$userid="s_tools_mail_pro";
$passwd="VlBvkdZgtp32gm9H";

// Connecting, selecting database
$link = mysql_connect($host, $userid, $passwd)
   or die('Could not connect: ' . mysql_error());
//echo 'Connected successfully';
mysql_select_db('s_tools_mail_prod') or die('Could not select database');

// Performing SQL query
$query = 'SELECT account FROM account WHERE is_approved = 1 AND when_moved IS NULL AND when_created IS NULL';
$result = mysql_query($query) or die('Query failed: ' . mysql_error());

// List results
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
   foreach ($line as $acct_to_link) {
       echo "$acct_to_link\n";
	   $link_attempt = shell_exec("remctl asregappprd9 wg-int-api link_group 'WIN Active Directory' office365-" . $acct_to_link . " jcowart office365:" . $acct_to_link);
	   if (chop($link_attempt) == '0') {
		echo "Matched\n";
            $update_query = 'UPDATE account SET when_moved = NOW() WHERE account="' . $acct_to_link . '"';
            $update_result = mysql_query($update_query) or die('Query failed: ' . mysql_error());
        }
   }
}

// Free resultset
mysql_free_result($result);

// Closing connection
mysql_close($link);
?>

