. $script_dir/common/upgrade

prep_upgrade()
{
    echo "# Preparing image upgrade..."
    mkdir -p $root_ov_old
    mkdir -p $root_ro_old
    if [ $root_type = 'blk' ]; then
        mount -t squashfs /dev/${ro_altpart} $root_ro_old
        mount -t overlayfs -o "ro,noatime,lowerdir=${root_ro_old},upperdir=${root_rw_old}" overlayfs $root_ov_old
    elif [ $root_type = 'ubi' ]; then
        mkdir -p /mnt/old-sysroot
        mount -t ubifs ubi:${ro_altpart} /mnt/old-sysroot
        mount -t squashfs /mnt/old-sysroot/sysroot $root_ro_old
        mount -t overlayfs -o "ro,noatime,lowerdir=${root_ro_old},upperdir=${root_rw_old}" overlayfs $root_ov_old
    fi
    reinstall_pkgs=$(mktemp)
    existing_pkgs=$(mktemp)
    echo "# Image Upgrade..." 
}

cleanup_upgrade()
{
    echo "# Cleanup image upgrade..."
    for f in $reinstall_pkgs $existing_pkgs
    do
        [ -f $f ] && rm -f $f
    done
    for d in $root_ov_old $root_ro_old /mnt/old-sysroot
    do
        [ -d $d ] && umount $d && rmdir $d
    done
}

copy_all_files()
{
    local exclude="
    /dev
    /proc
    /sys
    /run
    /var/lib/apt
    /var/lib/dpkg
    /var/lib/cumulus
    /mnt
    /etc/lsb-release
    /etc/cumulus/init/lsb-release
    "

    # File types:
    # (1) file belongs to a package
    # (2) file does NOT belog to a package
    # (3) file needs to be excluded

    list_installed_pkgs_in $ov_rootmnt $existing_pkgs

    find_files $root_rw_old $exclude | while read f
    do
        local _filepath="${f#$root_rw_old}"
        local pkgs=$(file_in_package $root_ov_old $_filepath)
        if [ -z "$pkgs" ]; then
            # if (2) then copy
            bury_copy "$f" "${ov_rootmnt}${_filepath}"
        else
            # if (1) then 
            #   if (pkg present in new slot) then
            #     copy file
            #   else
            #     dpkg-repackage on old slot && reinstall on new slow
            # * This should take care of the package conflicts like
            # * monit/jdoo etc. and will install new versions/configs
            for pkg in $(echo "$pkgs" | tr -d ' ' | tr ',' '\n')
            do
                if grep -Fxq "$pkg" $existing_pkgs ; then
                    bury_copy "$f" "${ov_rootmnt}${_filepath}"
                else
                    echo $pkg >> $reinstall_pkgs
                fi
            done
        fi
    done
    sort $reinstall_pkgs -uo $reinstall_pkgs 
}

reinstall_pkgs()
{
    local _old="/mnt/old"
    local mnt_old="${ov_rootmnt}${_old}"
    local new_pkgs=
    while read line; do new_pkgs="$new_pkgs $line"; done < $reinstall_pkgs;

    if [ -f "${root_rw_old}/var/lib/dpkg/status" ]; then
        mkdir -p $mnt_old && mount --bind /mnt/root-ov-old/ $mnt_old
 	fi

    upgrade_reinstall_packages "$new_pkgs" "$ov_rootmnt" "$_old"
    umount $mnt_old
}


