#!/bin/sh

set -e


ISO_IMAGE=$(cat /tmp/Upgrade-Auto/iso.file)

APT_CACHER_DIR='/var/cache/apt-cacher-ng'
APT_DIR='/var/cache/apt/archives'

MOUNT_POINT=

## Called at the end of the file
main() {
    if [ $(echo "${ISO_IMAGE}" | wc -l) -gt 1 ]
    then
	die "more than one ISO image detected: ${ISO_IMAGE}"
    fi

    if [ -d "${APT_CACHER_DIR}" ]
    then
	populate_apt_cacher_cache
    else
	populate_apt_cache
    fi
}

populate_apt_cache() {
    MOUNT_POINT='/media/cdrom'
    mount_iso "${ISO_IMAGE}" "${MOUNT_POINT}"

    if find "${MOUNT_POINT}" -type f -name '*.deb' | xargs -I{} cp {} "${APT_DIR}"
    then
	echo "APT cache directory populated"
    else
	die "unablo to populate APT cache"
    fi
}

populate_apt_cacher_cache() {

    MOUNT_POINT="${APT_CACHER_DIR}/_import"
    mount_iso "${ISO_IMAGE}" "${MOUNT_POINT}"
    APT_CACHER_IMPORT_LOG=/tmp/apt-cacher-import.log
    APT_CACHER_PORT=$(CreoleGet apt_cacher_port)

    CURRENT_DISTRIB=$(lsb_release --codename --short)
    NEXT_DISTRIB=$(awk '/^Suite:/ {print $2}' "${MOUNT_POINT}/dists/stable/Release")
    TMP_SL=/tmp/next-apt-sources.list

    # Build a temporary sources.list
    # EOLE references are OK
    cp /etc/apt/sources.list ${TMP_SL}
    sed -i -e "s,${CURRENT_DISTRIB},${NEXT_DISTRIB}," ${TMP_SL}
    
    # Clean apt cache
    rm -f /var/cache/apt/*cache.bin
    rm -f /var/lib/apt/lists/*Packages
    rm -f /var/lib/apt/lists/*Sources

    apt-get -o Dir::Etc::SourceList=${TMP_SL} update

    IMPORT_URL="http://localhost:${APT_CACHER_PORT}/acng-report.html?abortOnErrors=aOe&doImport=Start+Import&calcSize=cs&asNeeded=an"

    ERROR_PATTERN='(No appropriate files found in the _import directory|color=red)'
    wget -O "${APT_CACHER_IMPORT_LOG}" -q "${IMPORT_URL}"
    ERRORS=$(sed -n -E "/${ERROR_PATTERN}/ s,<[^>]*>,,gp" "${APT_CACHER_IMPORT_LOG}")
    if [ -n "${ERRORS}" ]
    then
	die "import log contains errors: ${ERRORS}"
    else
	echo "APT-CACHER cache populated"
    fi
}

mount_iso() {
    ISO="${1}"
    MOUNT_POINT="$2"

    [ -d "${MOUNT_POINT}" ] || mkdir "${MOUNT_POINT}"

    if ! mount -o loop,ro "${ISO}" "${MOUNT_POINT}"
    then
	die "unable to mount “${ISO}”"
    fi
}

die(){ echo 'Error:' $@ >&2; exit 1; }

_clean() {
    EXIT_CODE=$?

    # Do not abort on failure as we are in SIGHANDLER
    set +e

    # Make script idempotent
    umount "${MOUNT_POINT}" 2> /dev/null
    rmdir "${MOUNT_POINT}" 2> /dev/null

    # Use main script exit code
    return ${EXIT_CODE}
}

trap _clean EXIT

main $@
