#!/bin/sh
#
#       <debs-pool>
#
#       Run pool.sh to build a pool from important stuff in /cdrom
#
#       Copyright 2016 Canonical, Ltd..
#           Franz Hsieh (Franz) <franz.hsieh@canonical.com>
#
#       This program is free software; you can redistribute it and/or modify
#       it under the terms of the GNU General Public License as published by
#       the Free Software Foundation; either version 2 of the License, or
#       (at your option) any later version.
#
#       This program is distributed in the hope that it will be useful,
#       but WITHOUT ANY WARRANTY; without even the implied warranty of
#       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#       GNU General Public License for more details.
#
#       You should have received a copy of the GNU General Public License
#       along with this program; if not, write to the Free Software
#       Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
#       MA 02110-1301, USA.
# vim:ts=8:sw=8:et:tw=0

DEVICE=$1
RP=$2

[ -n "$DEVICE" -a -n "$RP" ]

mkdir -p $RP

# if $2 did not exsit, waiting for at most 10 seconds. (LP: #1193246)
for index in $(seq 1 10); do
    [ -b $DEVICE ] && break
    sleep 1
done

if [ ! -b $DEVICE ]; then
    # When there are two disks, we need find the correct disk.
    # If there are two Recovery Partitions, we will use the first one.
    DEV_RP=`blkid | grep 'PQSERVICE' | cut -d ':' -f1 | head -n1`
    if [ -z "$DEV_RP" ]; then
        exit 0
    fi
    if [ -b $DEV_RP ]; then
        DEVICE=$DEV_RP
    else
        exit 0
    fi
fi

mount -o ro $DEVICE $RP
if [ -f "$3/ubuntu.iso" ]; then
    mount -o loop $3/ubuntu.iso /cdrom
fi

[ -x /usr/share/ubuntu/scripts/pool.sh ] && \
    /usr/share/ubuntu/scripts/pool.sh
