#!/bin/sh
# Update partition script

source /usr/local/lib/utils

root_part_num=2
root_part=/dev/mmcblk0p${root_part_num}
root_mount=/tmp/rootfs

do_preinst()
{
    notif " 1/5 EXTRACT FIRMWARE UPDATE..^DO NOT TURN OFF THE CONSOLE"
    exit 0
}

do_postinst()
{
    ################
    # Fix recovery #
    ################
    notif " 2/5 FIX RECOVERY GPIO MANAGER"
    rw
    cp -a /tmp/funkey_gpio_management /usr/local/sbin/
    chmod +x /usr/local/sbin/funkey_gpio_management
    ro
    
    #################
    # Resize Rootfs #
    #################
    notif " 3/5 RESIZE ROOT FILESYSTEM^DO NOT TURN OFF THE CONSOLE"
    resize2fs ${root_part}
    if [ $? -ne 0 ]; then
    	notif " CANNOT RESIZE ROOT^FILESYSTEM"
    	exit 1
    fi

    #############
    # Copy OPKs #
    #############
    notif " 4/5 COPY OPKS TO USB MOUNT^DO NOT TURN OFF THE CONSOLE"
    
    # Mount Rootfs
    mkdir -p ${root_mount}
    mount -t ext4 ${root_part} ${root_mount}
    if [ $? -ne 0 ]; then
    	notif "CANNOT MOUNT ROOT^FILESYSTEM"
    	exit 1
    fi
    
    # Copy OPKs
    shared_partition=/mnt/
    mkdir -p "$shared_partition"
    cp -r ${root_mount}/usr/local/share/OPKs/* "$shared_partition"

    # Fix PCE opk name if necessary
    mv "$shared_partition"/Emulators/pce_mednaefn_funkey-s.opk "$shared_partition"/Emulators/pce_mednafen_funkey-s.opk 1>/dev/null 2>&1

    # Unmount Rootfs
    umount ${root_mount}
    if [ $? -ne 0 ]; then
    	notif "CANNOT UNMOUNT ROOT^FILESYSTEM"
    	exit 1
    fi

    #####################
    # Erase update file #
    #####################
    for file in $(ls /mnt/FunKey-*.fwu); do
        notif " 5/5 ERASE UPDATE FILE^DO NOT TURN OFF THE CONSOLE"
    	rm -f "${file}"
    done
    exit 0
}

echo $0 $1

case "$1" in
preinst)
    do_preinst
    ;;
postinst)
    do_postinst
    ;;
*)
    exit 1
    ;;
esac
