1#!/bin/bash
2# Copyright (c) 2015 The Chromium OS Authors. All rights reserved.
3# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5
6SCRIPT_DIR=$(dirname $(readlink -f $0))
7cd ${SCRIPT_DIR}/..
8
9LOGDIR=logs/stable-version
10ASSIGN_STABLE=site_utils/stable_images/assign_stable_images.py
11OPTIONS=()
12
13# STATUS is part hack, part safety valve.  The cron job that invokes
14# this script may be installed and enabled on both a primary and backup
15# server.  We skip running on the backup, but really, the backup
16# shouldn't have invoked this script in the first place...
17#
18# If we're not invoked on an autotest server at all, we assume this is
19# for testing, and invoke a dry run instead.
20#
21SERVER_STATUS=$(cli/atest server list $(hostname) 2>&1 |
22                  awk '/^Status *:/ { print $NF }')
23if [ "${SERVER_STATUS}" = "primary" ]; then
24  mkdir -p ${LOGDIR}
25  NOTIFY=(
26    chromeos-infra-eng@grotations.appspotmail.com
27  )
28else
29  if [ -n "${SERVER_STATUS}" ]; then
30    # must be backup
31    exit 0
32  fi
33  OPTIONS=( --dry-run )
34  NOTIFY=( ${LOGNAME}@google.com )
35fi
36
37# Redirect onto a log file.  For debug purposes, skip redirection if
38# there's a command line argument (we ignore what the argument is), or
39# if there's no log directory.
40#
41TAG=$(date '+%Y-%W')
42if [ $# -eq 0 -a -d ${LOGDIR} ]; then
43    LOGFILE="update-${TAG}.log"
44    exec >>${LOGDIR}/${LOGFILE} 2>&1
45fi
46
47trap 'rm -f ${TMPFILE}' EXIT
48TMPFILE=$(mktemp)
49
50date
51$ASSIGN_STABLE "${OPTIONS[@]}" 2>&1 | tee ${TMPFILE}
52echo
53
54# If we have a log directory, clean it up, and send e-mail notification.
55# The log files change name each week, so by throwing out all but the
56# most recent 14 files, we keep about 3 months of history, plus this
57# week's log.
58#
59if [ -d ${LOGDIR} ]; then
60    SUBJECT="Stable version update summary ${TAG}"
61    site_utils/gmail_lib.py -s "${SUBJECT}" "${NOTIFY[@]}" <${TMPFILE}
62    rm -f $(ls -r ${LOGDIR}/update-*.log | sed '1,14 d')
63fi
64