#!/bin/bash

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

SCRIPT_ROOT=$(dirname "$(readlink -f "$0")")
. "${SCRIPT_ROOT}/common.sh" || exit 1

# Script must run inside the chroot
assert_inside_chroot

assert_not_root_user

# Flags
DEFINE_string group "" \
  "The update group, required."
DEFINE_string board "${DEFAULT_BOARD}" \
  "Board for which the image was built"
DEFINE_string disk_layout "base" \
  "The disk layout type to use for this image."
DEFINE_string from "" \
  "Directory containing ${FLATCAR_PRODUCTION_IMAGE_NAME}"
DEFINE_string output_root "${DEFAULT_BUILD_ROOT}/images" \
  "Directory in which to place image result directories (named by version)"
DEFINE_boolean replace ${FLAGS_FALSE} \
  "Overwrite existing output, if any."

# include upload options
. "${BUILD_LIBRARY_DIR}/release_util.sh" || exit 1

show_help_if_requested "$@"

# Usually unneded, so just leave this option hidden.
DEFINE_integer build_attempt 1 \
  "The build attempt for this image build."

# Parse command line
FLAGS "$@" || exit 1
eval set -- "${FLAGS_ARGV}"

# Die on any errors.
switch_to_strict_mode

check_gsutil_opts

if [[ -z "${FLAGS_board}" ]] ; then
  die_notrace "--board is required."
fi

if [[ -z "${FLAGS_group}" ]] ; then
  die_notrace "--group is required."
fi

. "${BUILD_LIBRARY_DIR}/modify_image_util.sh"

start_modify_image

info "Replacing /etc/flatcar/update.conf"
sudo mkdir -p "${ROOT_FS_DIR}/etc/flatcar"
sudo_clobber "${ROOT_FS_DIR}/etc/flatcar/update.conf" <<EOF
GROUP=${FLAGS_group}
EOF

finish_modify_image
command_completed
