#!/bin/sh

# Copyright (c) 2010 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

# This scripts performs update of stateful partition directories useful for
# dev_mode.

. /usr/lib/shflags

# Constants for states.
CLEAN_STATE="clean"
OLD_STATE="old"

DEFINE_string stateful_change "${OLD_STATE}" \
  "The state of the new stateful partition - used in update testing."

FLAGS "$@" || exit 1

# Die on error.
set -e

remove_quotes() {
  echo "$1" | sed -e "s/^'//; s/'$//"
}

update_dev_image () {
  LSB_RELEASE="/etc/lsb-release"
  STATEFUL_DIR="/mnt/stateful_partition"

  if [ -n "${FLAGS_ARGV}" ]; then
    BASE_UPDATE_URL=$(remove_quotes "${FLAGS_ARGV}")
  else
    if [ -f "${STATEFUL_DIR}${LSB_RELEASE}" ]; then
      DEVSERVER_URL=$(grep CHROMEOS_DEVSERVER ${STATEFUL_DIR}${LSB_RELEASE} |
          cut -f 2 -d '=')
    fi
    if [ -z "${DEVSERVER_URL}" ]; then
      DEVSERVER_URL=$(grep CHROMEOS_DEVSERVER ${LSB_RELEASE} | cut -f 2 -d '=')
    fi
    # Sanity check.
    if [ -z "${DEVSERVER_URL}" ]; then
      echo >&2 "No CHROMEOS_DEVSERVER URL found in lsb-release file"
      exit 1
    fi
    # Devserver URL should never contain "/update"
    DEVSERVER_URL=$(echo ${DEVSERVER_URL} | sed -e 's#/update##')
    BASE_UPDATE_URL="${DEVSERVER_URL}/static"
  fi

  STATEFUL_UPDATE_URL="${BASE_UPDATE_URL}/stateful.tgz"
  echo "Downloading stateful payload from ${STATEFUL_UPDATE_URL}"
  # Download and unzip directories onto the stateful partition.
  eval "wget -qS -T 300 -O - \"${STATEFUL_UPDATE_URL}\"" |
      tar --ignore-command-error --overwrite --directory=${STATEFUL_DIR} -xz
  echo >&2 "Successfully downloaded update"

  if [ ! -d "${STATEFUL_DIR}/var_new" ] ||
      [ ! -d "${STATEFUL_DIR}/dev_image_new" ]; then
    echo >&2 "Missing var or dev_image in stateful payload."
    return 1
  fi
}

update_old_state () {
  echo >&2 "Performing standard stateful update."
  echo -n "" > "${STATEFUL_DIR}/.update_available"
}

update_clean_state () {
  echo >&2 "Restoring state to factory_install with dev_image."
  echo -n "clobber" > "${STATEFUL_DIR}/.update_available"
}

main () {
  if update_dev_image; then
    if [ "${FLAGS_stateful_change}" = "${OLD_STATE}" ]; then
      update_old_state
    elif [ "${FLAGS_stateful_change}" = "${CLEAN_STATE}" ]; then
      update_clean_state
    else
      echo >&2 "Invalid state given to stateful update.  Aborting..."
      return 1
    fi
  else
    return 1
  fi
}

main $@
