#!/bin/bash
# Run this script once the rpm files have been stored in /tmp in the 
# current side. Install the files onto the changeover side.
# Once processed with model number, this version does not check
# that the new model matches the installed model.
#
# NOTE: fstab files will be fixed by changeover/rollback function.
#
# First problem is "where are we?"
#

export PATH="$PATH:/usr/bin:/bin:/sbin:/usr/sbin:/mnt/apps/bin"

if [ $# -lt 1 ]
then
    echo "USAGE: rpm_post_install <Model>"
    exit 1
fi

#OPIN API mandates we pass in MODEL-FileSystems.pkg but we only need MODEL
MODEL=`echo $1 | sed 's/-FileSystems.pkg//g'`
ROOTNEXTNAME=rootfs2
ROOTNEXTDEV=3
APPSNEXTDEV=5
APPSNEXTNAME=apps2
KERNELNEXTNAME=kernel2
KERNELNEXTDEV=1
if [ `mount|grep rootfs2|wc -l` -eq 1 ]
then 
    ROOTNEXTNAME=rootfs1
    APPSNEXTNAME=apps1
    KERNELNEXTNAME=kernel1
    KERNELNEXTDEV=0
    ROOTNEXTDEV=2
    APPSNEXTDEV=4
fi

UPDATE_ERROR=0
UPDATE_LOG=/tmp/update.log

# Between the 2nd Gen and 1st Gen boards we need to run a different ubimkvol
# on 2nd Gen its already built in via Busybox, but 1st gen we include it 
# as part of the update rpm.
if [ -f "/usr/sbin/ubimkvol" ]
then
    # This is a Gen2 board, with the busybox UBI utils already installed
    UBIMKVOL=/usr/sbin/ubimkvol

    #Gen2 update manager - we can choose where to extract to the transfer partition.
    TEMP_DIR=/mnt/transfer
    RAMFS_DIR=/tmp
else
    #Gen 1 Must use the version supplied with the RPM
    UBIMKVOL=/tmp/rpm/ubimkvol

    #original update-manager never had option to specifiy install location, 
    #so we MUST specifiy the OLD defaults
    TEMP_DIR=/tmp
    RAMFS_DIR=/mnt/transfer
fi

#Partition sizes should match those specified in ubi.ini 
KERNEL_SIZE=2306867
ROOTFS_SIZE=17301504
APPSFS_SIZE=30723277

TRANSFERFS_SIZE=24117248
TRANSFERNEXTDEV=6
TRANSFERNEXTNAME=transfer


cleanup()
{
    rm -rf /mnt/transfer/*
    rm -rf /tmp/rpm
}

remove_partition() # partition_number partition_name
{
    echo "Remove $2 "
    ubinfo /dev/ubi0_$1 1>> ${UPDATE_LOG} 2>&1
    if [ $? -eq 0 ]; then
        ubirmvol /dev/ubi0 -n $1 
        if [ $? -eq 0 ]; then
            sync
            echo "OK"
        else
            UPDATE_ERROR=1
            echo "Error ubirmvol"
            echo "Error Removing $2"
            echo "UPDATE FAILED"
            cleanup
            exit 8
        fi
    else
        echo "$2 partition already removed"
    fi
}

create_partition() #device name size static_or_dynamic
{
    echo "Create $2 "
    ${UBIMKVOL} /dev/ubi0 -n $1 -N $2 -s $3 -t $4 1>> ${UPDATE_LOG} 2>&1
    if [ $? -eq 0 ]; then
        sync
        echo "OK"
    else
        UPDATE_ERROR=1
        echo "Failed to create $2"
        echo "UPDATE FAILED"
        cleanup
        exit 9
    fi
}


update_partition() #device sourcefile targetfile name
{
    echo "update $4 "
    cd ${TEMP_DIR}
    tar -xzf $2 --extract $3 -C ${RAMFS_DIR} 1>> ${UPDATE_LOG} 2>&1
    if [ $? -eq 0 ]; then
        ubiupdatevol /dev/ubi0_$1 ${RAMFS_DIR}/$3 1>> ${UPDATE_LOG} 2>&1
        if [ $? -ne 0 ]; then    
            UPDATE_ERROR=1
            echo "Error ubiupdatevol $4"
            echo "UPDATE FAILED"
            cleanup
            exit 10;
        else
            echo "OK"
        fi

        rm -f ${RAMFS_DIR}/$3
    else
        echo "Error extracting $3" 
        echo "UPDATE FAILED"
        cleanup
        exit 11;
    fi
}


echo "rpm_post_install: $MODEL on $APPSNEXTNAME"

echo "== UPDATE ==" 1>> ${UPDATE_LOG} 2>&1
date 1>> ${UPDATE_LOG} 2>&1
echo "MODEL=${MODEL}" >> ${UPDATE_LOG} 2>&1


#only install to the correct model
VALIDATED=0
if [ ${MODEL} = "V2-V1000" ] || [ ${MODEL} = "V2-V2000" ] || [ ${MODEL} = "EH400" ]; then
    grep ${MODEL} /mnt/apps/data/config/InternalID
    if [ $? -eq 0 ]; then
        VALIDATED=1
    fi
fi

if [ ${MODEL} = "EHS400" ]; then
    if [ -f /mnt/apps/data/db/carddb ]; then
        VALIDATED=1
    fi
fi

if [ ${MODEL} = "FORCE" ]; then
    VALIDATED=1
fi

if [ ${VALIDATED} -eq 0 ]; then
    echo "Error - Invalid Model ${MODEL}"
    exit 1
fi

# untar the sql files to /sbin
tar xzf /tmp/rpm/sql_scripts.tgz -C /tmp

# delete/recreate transfer, in case size changes and we need to steal some space from it. 
umount /mnt/transfer 1>> ${UPDATE_LOG} 2>&1
if [ $? -eq 0 ]; then 
    remove_partition ${TRANSFERNEXTDEV} ${TRANSFERNEXTNAME}
    create_partition ${TRANSFERNEXTDEV} ${TRANSFERNEXTNAME} ${TRANSFERFS_SIZE} dynamic
    ubiupdatevol /dev/ubi0_${TRANSFERNEXTDEV} -t 1>> ${UPDATE_LOG} 2>&1
    if [ $? -eq 0 ]; then
        sync
        mount -t ubifs ubi0_6 -o sync /mnt/transfer 1>> ${UPDATE_LOG} 2>&1
        if [ $? -eq 0 ]; then 
            echo "Transfer mount OK"
        else
            echo "Error remount transfer"
            UPDATE_ERROR=1
        fi
    else
        echo "ubiupdatevol transfer fail" 
        UPDATE_ERROR=1
    fi  
else
    UPDATE_ERROR=1
    echo "Failed to unmount /mnt/transfer"
fi

sync

if [ ${UPDATE_ERROR} -ne 0 ]; then
    echo "UPDATE FAILED"
    cleanup
    exit 1;
fi


#
# Test the update package integrity
#
echo "Checking Package Integrity..."
cd /tmp/rpm
/mnt/apps/bin/update-manager ${MODEL}-FileSystems.pkg ${TEMP_DIR}
if [ $? -ne 0 ]; then
    echo "Package failed integrity check"  
    echo "UPDATE FAILED"
    cleanup
    exit 2
else
    echo "Integrity OK"
fi

sync

cd ${TEMP_DIR}
rm -f manifest.xml

#delete and re-create remaining partitions. 
echo "Remove Existing Partitions"
remove_partition ${KERNELNEXTDEV} ${KERNELNEXTNAME}
remove_partition ${ROOTNEXTDEV}   ${ROOTNEXTNAME}
remove_partition ${APPSNEXTDEV}   ${APPSNEXTNAME}

echo "Create New Partitions"
create_partition ${KERNELNEXTDEV} ${KERNELNEXTNAME} ${KERNEL_SIZE} static
create_partition ${ROOTNEXTDEV}   ${ROOTNEXTNAME}   ${ROOTFS_SIZE} dynamic
create_partition ${APPSNEXTDEV}   ${APPSNEXTNAME}   ${APPSFS_SIZE} dynamic

echo "update Partitions"
update_partition ${KERNELNEXTDEV} ${MODEL}.Package.tgz ${MODEL}.uImage-A7.img ${KERNELNEXTNAME}
update_partition ${ROOTNEXTDEV}   ${MODEL}.Package.tgz rootfs1.img            ${ROOTNEXTNAME}
update_partition ${APPSNEXTDEV}   ${MODEL}.Package.tgz appsfs.img             ${APPSNEXTNAME}

sync

#
# Update Bootloader/Bootstrap
#
cd /tmp/rpm
echo "rpm_post_install: Updating Loader."

/tmp/rpm/nanddump -f /tmp/rpm/mtd0.bin -s 0x0 /dev/mtd0 1>> ${UPDATE_LOG} 2>&1
if [ $? -eq 0 ]; then
    /tmp/rpm/update_bootstrap_nand write /tmp/rpm/mtd0.bin /tmp/rpm/bootstrap_nand.bin /tmp/rpm/u-boot.bin 1>> ${UPDATE_LOG} 2>&1
    if [ $? -eq 0 ]; then
        /tmp/rpm/flashcp -v /tmp/rpm/mtd0.bin /dev/mtd0 1>> ${UPDATE_LOG} 2>&1
        if [ $? -ne 0 ]; then
            echo "Error updating loader" 
            UPDATE_ERROR=1
        fi
    else
        echo "Error updating loader"  
        UPDATE_ERROR=1
    fi
else
    echo "Error updating loader" 
    UPDATE_ERROR=1
fi

rm -f /tmp/rpm/update_bootstrap_nand /tmp/rpm/nanddump /tmp/rpm/flashcp /tmp/rpm/bootstrap_nand.bin /tmp/rpm/u-boot.bin
sync

if [ ${UPDATE_ERROR} -ne 0 ]; then
    echo "Error updating loader"
    echo "UPDATE FAILED"
    cleanup
    exit 6
else
    echo "Loader update OK"
fi

if [ ! -f /etc/sysconfig/.htpasswd ]; then
    #This is a Gen1 boa build, must now sync system admin password with lighty on next Gen2 boot
    #Bootfreeze will do the work for us, just let it know it needs to run.

    mkdir -p /mnt/backup
    mount -t ubifs ubi0:$APPSNEXTNAME /mnt/backup
    if [ $? -eq 0 ]
    then
        # set flag in /mnt/apps/bin for bootfreeze to look for
        touch /mnt/backup/bin/LightyFirstInstall
        umount /mnt/backup
    else
        echo "ERROR WebServer mount failed"
        UPDATE_ERROR=1
    fi
fi

if [ ${UPDATE_ERROR} -ne 0 ]; then
    echo "Error during WebServer Configuration "
    echo "UPDATE FAILED"
    cleanup
    exit 7
fi

cleanup
sync

echo "rpm_post_install: complete."
exit 0
