#!/bin/bash

if [[ -z "$1" ]] || [[ "$1" != /*  ]]; then
    echo "Usage: $0 <emmc_dev> [--net-config]"
    exit 1
fi

shopt -s extglob  # For extended globbing of /boot/*.{txt,ini,...}

cmdline_args="$*"

function arg_present() {
    for arg in ${cmdline_args}; do
        if [ "${arg}" == "$1" ]; then
            return 0
        fi
    done
    
    return 1
}

function msg() {
    echo " * $1"
}

NET_CONFIG_FILES=(
    dnsmasq.conf
    hostapd.conf
    static_ip.conf
    wpa_supplicant.conf
)

emmc_dev=$1

source /tmp/disk_info

msg "SD card device is ${DISK_DEV}"

root_info=$(fdisk -l -o device,start,end,size ${DISK_DEV} | grep "${ROOT_DEV}")
root_info=(${root_info})

root_end_sector=${root_info[2]}
total_size=$(((root_end_sector + 1) * 512 / 10485760))  # x 10MB

msg "Unmounting all EMMC partitions"
umount ${emmc_dev}* &>/dev/null
partx -d ${emmc_dev} &>/dev/null

msg "Copying ${total_size}0MB from ${DISK_DEV} to ${emmc_dev}"
dd if=${DISK_DEV} of=${emmc_dev} bs=10M count=${total_size} status=none
sync
partx -a ${emmc_dev} &>/dev/null

sleep 1

msg "Removing data partition from EMMC"
fdisk >/dev/null ${emmc_dev} <<END
d
3
w
END
sync

msg "Mounting ${emmc_dev}p1 boot partition"
mkdir -p /data/.emmc_boot
mount ${emmc_dev}p1 /data/.emmc_boot
cd /data/.emmc_boot

if [[ -f toemmc.conf ]]; then
    msg "Removing toemmc.conf"
    rm -f toemmc.conf
fi

if [[ -f /boot/factory-defaults.tar.xz ]]; then
    msg "Copying factory defaults"
    cp /boot/factory-defaults.tar.xz .
fi

if arg_present "--net-config"; then
    msg "Copying network configuration"
    for file in ${NET_CONFIG_FILES[*]}; do
        path="/data/etc/${file}"
        test -s ${path} || continue
        cp ${path} .
        msg "Copied ${file}"
    done
fi

msg "Cleaning up"
cd - >/dev/null
umount /data/.emmc_boot
rmdir /data/.emmc_boot

msg "Done!"
