#!/bin/sh -e
# Copyright 2020 Oliver Smith, Undef
# SPDX-License-Identifier: GPL-3.0-or-later
# Modified from https://gitlab.com/postmarketOS/postmarketos-ondev/-/blob/master/ondev-prepare-internal-storage.sh

# Sanity check
part_install="$(df -T / | awk '/^\/dev/ {print $1}')"
installer_part="$(realpath /dev/disk/by-label/installer)"
if [ "$installer_part" != "$part_install" ]; then
    echo "ERROR: Unexpected installer partition; installer is not" \
        "running from detected partition. Bailing!"
    echo "This situation typically arises when the installer image" \
        "exists on both embedded and removable storage."
    echo "(installer_part: '$installer_parth')"
    echo "(part_install: '$part_install')"
    exit 1
fi

echo " === prepare-internal-storage === "
set -x

dev_installer=${EXTERNAL_SOURCE}
dev=${INTERNAL_TARGET}
dev_boot=""
dev_root=""
boot_filesystem="ext4"
mb_boot_part_start="8"
mb_boot="512"

# Create partition table
partitions_create() {
    parted -s "${dev}" mktable msdos
    # Boot Partition
    parted -s "${dev}" mkpart primary "${boot_filesystem}" \
        "${mb_boot_part_start}M" "${mb_boot}M"
    # Root Partition
    parted -s "${dev}" mkpart primary "${mb_boot}M" "100%"
    parted -s "${dev}" set 1 boot on
    partprobe "${dev}"
}

# Try to find the boot and root partitions for 10 seconds
partitions_find() {
    for i in $(seq 1 100); do
        if [ -e "${dev}p1" ] && [ -e "${dev}p2" ]; then
            dev_boot="${dev}p1"
            dev_root="${dev}p2"
            return
        elif [ -e "${dev}1" ] && [ -e "${dev}2" ]; then
            dev_boot="${dev}1"
            dev_root="${dev}2"
            return
        fi
        sleep 0.1
    done
    echo "Failed to find boot and root partition after creating" \
        "partition table (dev: '$dev')"
    exit 1
}

# Format the boot partition
boot_format() {
    mkfs.ext4 -F -q -L boot "${dev_boot}"
}

# Copy the boot partition contents from /boot 
boot_copy() {
    local target_path="/mnt/install-boot"
    local source_path="/boot"

    mkdir -p "${target_path}"
    mount "${dev_boot}" "${target_path}"
    cp -a -r "${source_path}"/* "${target_path}"
    umount "${target_path}"
}

partitions_create
partitions_find
boot_format
boot_copy
