#!/bin/bash -e
# Copyright (C) 2016-2017 Endless Mobile, Inc.
# Licensed under the GPLv2

# arguments checking
if [ $# -lt 1 ]; then
  echo "Usage: $0 <EOS device>" >&2
  exit 1
fi

root_disk="$1"

# udev might still be busy probing the disk, meaning that it will be in use.
udevadm settle

# take current partition table
parts=$(sfdisk -d "$root_disk")

check_partition_exists() {
  local name=${1:?No name supplied to ${FUNCNAME[0]}}
  local guid=${2:?No GUID supplied to ${FUNCNAME[0]}}

  if ! echo "$parts" | grep -iq "type=$guid"; then
    echo "$0: $name partition not found" >&2
    exit 1
  fi
}

esp_guid="C12A7328-F81F-11D2-BA4B-00A0C93EC93B"
bios_boot_guid="21686148-6449-6E6F-744E-656564454649"
dps_root_guid="4F68BCE3-E8CD-4DB1-96E7-FBCAF984B709"

check_partition_exists "ESP" "$esp_guid"
check_partition_exists "BIOS boot" "$bios_boot_guid"
check_partition_exists "Endless OS root" "$dps_root_guid"
# If any other partitions exist, the call to sfdisk with the modified table
# will fail due to type=UUid being invalid with 'label: dos'

# “See if you can use ${variable//search/replace} instead.” For some of these,
# we cannot.
# shellcheck disable=SC2001
{
# Reset partition indexes
parts=$(echo "$parts" | sed -e "s/^\/[^: ]\+//")

# GPT -> DOS
parts=$(echo "$parts" | sed -e "s/label: gpt/label: dos/")

# Set ESP partition type to EF
parts=$(echo "$parts" | sed -e "s/, type=$esp_guid/, type=EF/")
# Remove BIOS boot partition (but leave its former contents intact)
parts=$(echo "$parts" | grep -v "$bios_boot_guid")
# Set MBR partition type on root partition, and mark as bootable (not strictly
# true, but our MBR does not care - some BIOSes don't consider a drive to be
# bootable without it)
parts=$(echo "$parts" | sed -e "s/, type=$dps_root_guid/, type=83, bootable/")
# Remove partition UUIDs and GPT attributes
parts=$(echo "$parts" | sed -e "s/, \(uuid\|attrs\)=[^\s,]\+//g")
}

echo "$parts" | sfdisk --force --no-reread "$root_disk"
udevadm settle
partprobe "${root_disk}"
udevadm settle

# Set marker on 4th partition so that the partition gets enlarged to fill the
# disk on first boot
printf "\xdd" | dd of="$root_disk" bs=1 count=1 seek=498 conv=notrunc
udevadm settle
