#!/usr/bin/env bash
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


# Builds a UEFI VM using virt-install, and then creates a
# GCP image from it.
#
# Usage:
#  ./gce-uefi.sh <name> <kickstart> <gcp directory>
#     *name* of the GCP image to create. It will be removed if
#       it already exists.
#     a path to a *kickstart* file. No pre-processing is performed.
#     a *gcp directory* to use for storing the intermediate image file.
#
# Requirements:
#  virt-install
#  virsh
#  qemu-img
#  gcloud (pre-authenticated)
#  gsutil (pre-authenticated)
#
set -uf -o pipefail

if [ "$#" -ne 3 ]; then
  echo 'usage: gce-uefi.sh <name> <kickstart> <gcp directory>'
  echo 'example: gce-uefi.sh f33 fedora-cloud-base.ks gs://your-bucket/tmp/'
  exit 1
fi

name=$1
ks_path=$(realpath "$2")
bucket=$3
root="/tmp/virt-install-$RANDOM"
mkdir -p "$root"/ks

echo "name=$name"
echo "ks_path=$ks_path"
echo "build_dir=$root"

pushd $root
cp "$ks_path" ks/ks.cfg
qemu-img create -f raw disk.raw 20G
virt-install \
  --name "$name" \
  --ram 4096 \
  --vcpus 4 \
  --disk path=disk.raw,size=20 \
  --boot uefi \
  --accelerate \
  --location https://dl.fedoraproject.org/pub/fedora/linux/development/rawhide/Everything/x86_64/os \
  --initrd-inject ks/ks.cfg \
  --extra-args 'ks=file://ks.cfg'

gcloud compute images delete "$name" --quiet
tar --format=oldgnu -Sczf compressed-image.tar.gz disk.raw
gsutil cp compressed-image.tar.gz "$bucket"
gcloud compute images create "$name" \
  --source-uri "${bucket}compressed-image.tar.gz" \
  --guest-os-features=UEFI_COMPATIBLE

virsh destroy "$name"
virsh undefine "$name" --nvram
