#!/bin/bash

set -e

export VG=xenvg
export INSTALLLV=s_install_hda
export INSTALLPATH="/dev/$VG/$INSTALLLV"
export UPDATEPATH="/dev/$VG/update_$INSTALLLV"
export MAPPERPATH="/dev/mapper/$VG-update_$INSTALLLV"
export MOUNTDIRS="/dev /proc /sys"

clean_up() {
    set +e
    
    for i in $MOUNTDIRS; do
        umount "/mnt/install$i"
    done
    
    umount /mnt/install
    kpartx -d "$UPDATEPATH"
    lvchange -a y "$UPDATEPATH"
    lvrename "$UPDATEPATH" "$INSTALLPATH"
    exit 0
}

trap clean_up ERR

lvchange -a n "$INSTALLPATH"
lvrename "$INSTALLPATH" "$UPDATEPATH"
lvchange -a ey "$UPDATEPATH"
kpartx -a "$UPDATEPATH"

mkdir -p /mnt/install
mount "${MAPPERPATH}1" /mnt/install

for i in $MOUNTDIRS; do
    mount --bind $i "/mnt/install$i"
done

chroot /mnt/install aptitude update
chroot /mnt/install aptitude dist-upgrade

clean_up
