1#!/bin/bash 
2
3# Copyright (c) 2011 The Chromium OS Authors. All rights reserved.
4# Use of this source code is governed by a BSD-style license that can be
5# found in the LICENSE file.
6
7# Script to convert a recovery image into an SSD image. Changes are made in-
8# place.
9
10usage() {
11  cat <<EOF
12Usage: $PROG <image> [--force] [--cgpt=/path/to/cgpt]
13
14In-place converts recovery <image> into an SSD image. With --force, does not
15ask for confirmation from the user. Use --cgpt= to specify cgpt binary location.
16
17EOF
18  exit 1
19}
20
21if [ $# -lt 1 ] || [ $# -gt 3 ]; then
22  usage
23else
24  IMAGE=$1
25  shift
26fi
27
28for arg in $*; do
29  case "$arg" in
30  --force)
31    IS_FORCE=$arg
32    ;;
33  --cgpt=*)
34    GPT=${arg#--cgpt=}
35    ;;
36  *)
37    usage
38    ;;
39  esac
40done
41
42# Load common constants (and use GPT if set above) and variables.
43. "$(dirname "$0")/common_minimal.sh"
44
45type -P $GPT &>/dev/null ||
46  { echo "cgpt tool must be in the path or specified via --cgpt"; exit 1; }
47
48# Abort on errors.
49set -e
50
51if [ "${IS_FORCE}" != "--force" ]; then
52  echo "This will modify ${IMAGE} in-place and convert it into an SSD image."
53  read -p "Are you sure you want to continue (y/N)?" SURE
54  SURE="${SURE:0:1}"
55  [ "${SURE}" != "y" ] && exit 1
56fi
57
58kerna_offset=$(partoffset ${IMAGE} 2)
59kernb_offset=$(partoffset ${IMAGE} 4)
60# Kernel partition sizes should be the same.
61kern_size=$(partsize ${IMAGE} 2)
62
63# Move Kernel B to Kernel A.
64kernb=$(make_temp_file)
65echo "Replacing Kernel partition A with Kernel partition B"
66extract_image_partition ${IMAGE} 4 ${kernb}
67replace_image_partition ${IMAGE} 2 ${kernb}
68
69# Overwrite the vblock.
70stateful_dir=$(make_temp_dir)
71tmp_vblock=$(make_temp_file)
72mount_image_partition_ro ${IMAGE} 1 ${stateful_dir}
73sudo cp ${stateful_dir}/vmlinuz_hd.vblock ${tmp_vblock}
74# Unmount before overwriting image to avoid sync issues.
75sudo umount ${stateful_dir}
76echo "Overwriting kernel partition A vblock with SSD vblock"
77sudo dd if=${tmp_vblock} of=${IMAGE} seek=${kerna_offset} bs=512 conv=notrunc
78
79# Zero out Kernel B partition.
80echo "Zeroing out Kernel partition B"
81sudo dd if=/dev/zero of=${IMAGE} seek=${kernb_offset} bs=512 count=${kern_size} conv=notrunc
82echo "${IMAGE} was converted to an SSD image."
83