#!/bin/bash

# Copyright (C) 2004-2010 Centro de Computacao Cientifica e Software Livre
# Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
#
# This file is part of le-base
#
# le-base is free software; you can redistNameribute 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 distNameributed 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.

#------------------------------------------------------------------------------

export DEBIAN_FRONTEND=noninteractive

editDistro()
{
    log "Editing $DISTROBASE ..."
    initFiles
    # Edits live image

    for file in $(ls "$SCRIPTSDIR"); do
        if [ -x "$SCRIPTSDIR/$file" ] && egrep -q '^[0-9]{2}-[a-z-]+' <<< "$file"; then
            echo "$file"
            #read -p "PAUSADO ..."
            if ! "$SCRIPTSDIR/$file" $1; then
                log "Error: While running the "$SCRIPTSDIR/$file""
                return 1
            fi
        fi
    done

    return 0
}

regenerateManifest()
{
    log "Regenerating manifest list ..."
    chmod +w "$CDDIR"/casper/filesystem.manifest
    chroot "$CHROOTDIR" dpkg-query -W --showformat='${Package} ${Version}\n' > \
        "$CDDIR"/casper/filesystem.manifest

    if [ "$DISTRO" == "Linux_Educacional_4.0" ]; then
        cp "$CDDIR"/casper/filesystem.manifest \
            "$CDDIR"/casper/filesystem.manifest-desktop
        for package in $(cat "$INSTLIST" | cut -d '=' -f1 | grep -v "^#"); do
            sed -i "/$package/d" "$CDDIR"/casper/filesystem.manifest-desktop
        done
        for pkg in $(cat "$INSTLIST"-desktop | cut -d'=' -f1 | grep -v "^#"); do
            ( printf "$pkg "; chroot "$CHROOTDIR" apt-cache showpkg "$pkg" |
                grep "^[0-9]" | tail -n1 | cut -d ' ' -f1 ) >> \
                    "$CDDIR"/casper/filesystem.manifest-desktop
        done
    elif [ "$DISTRO" == "Linux_Educacional_5" ]; then
        cat "$INSTLIST"-remove >> "$CDDIR"/casper/filesystem.manifest-remove
    fi
    return 0
}

compressFS()
{
    log "Compressing squash image ..."
    if [ -n "$(cat $MOUNTLIST)" ]; then
        log "Error to umount $(cat $MOUNTLIST | tr '\n' ' ')"
        return 1
    fi

    rm -f "$CDDIR"/casper/filesystem.squashfs
    mksquashfs "$CHROOTDIR" "$CDDIR"/casper/filesystem.squashfs -comp gzip

    du -sx --block-size=1 "$CHROOTDIR" | cut -f1 > "$CDDIR"/casper/filesystem.size

    return 0
}

extractISO()
{
    log "Extracting $1 ..."
    initFiles

    mount -o loop $1 "$TMP"/"$DISTROBASE" && log "$TMP/$DISTROBASE" >> "$MOUNTLIST"

    rsync --exclude=/casper/filesystem.squashfs -a "$TMP"/"$DISTROBASE"/ "$CDDIR"\
        || return 1

    unsquashfs "$TMP"/"$DISTROBASE"/casper/filesystem.squashfs || return 1
    mv -f "$SQUASHIMAGE" "$CHROOTDIR" || return 1

    umount "$TMP"/"$DISTROBASE" && removeMountList "$TMP"/"$DISTROBASE"

    return 0
}

createISO()
{
    log "Generating live ISO ..."

    # Calculates MD5
    cd "$CDDIR"/
    rm -f md5sum.txt
    find -type f -print0 | xargs -0 md5sum |
        egrep -v 'isolinux/boot.cat|md5sum.txt' | tee md5sum.txt

    # Generates ISO file
    genisoimage -D -r -V "$DISTRO" -cache-inodes -J -l -b \
    isolinux/isolinux.bin -c isolinux/boot.cat -no-emul-boot -boot-load-size \
    4 -boot-info-table -o "$DISTROISO".iso "$CDDIR"

    log "Generating iso checksum ..."
    md5sum "$DISTROISO.iso" > "$DISTROISO.md5"

    # Move generated file, if an output was specified
    if test -n "$OUTPUT"; then
        mv "$DISTROISO.iso" "$OUTPUT"
        mv "$DISTROISO.md5" "$OUTPUT.md5"
    fi
}

initFiles()
{
    mkdir -p "$TMP" || return 1
    mkdir -p "$TMP"/"$DISTROBASE" "$CDDIR" "$LOGDIR" || return 1
    touch "$MOUNTLIST" || return 1
}

replaceIso()
{
    if [ -e "$CDDIR" ]; then
        log "Want to replace the current image? [y/N]"
        read ack
        if [ "$ack" == "y" ]; then
            log "Cleaning temporary directory ..."

            rm -rf "$TMP"/* "$CHROOTDIR" "$CDDIR" "$SQUASHIMAGE" || return 6
            #$0 --clean --dist $1 || exit 6
        else
            log "Extraction canceled!"
            return 1
       fi
    fi

    return 0
}

log()
{
    if "$LOGINFO" && [ "$1" ]; then
        echo "$@" | tee -a "$LOGFILE"
        logger -t le-gera-iso "$@"
    elif [ "$1" ]; then
        echo "$@"
    else
        tee -a "$LOGFILE"
    fi
}

#------------------------------------------------------------------------------
# Sets configuration variables

DIR=$(readlink -f "$0")
. "`dirname "$(echo "$DIR")"`/common.sh"

nextDist=false
nextAll=false
iso=false
clean=false
all=false
dist=false
edit=false
host=false
mirror=false
nextHost=false
nextMirror=false
output=false

for opc in "$@"; do
    case "$opc" in
        --dist)
            dist=true
            nextDist=true
        ;;
        --all)
            all=true
            nextAll=true
        ;;
        --edit)
            edit=true
        ;;
        --iso)
            iso=true
        ;;
        --clean)
            clean=true
        ;;
        --output)
            output=true
        ;;
        -bash)
            bash
            exit 0
        ;;
        --host)
            host=true
            nextHost=true
        ;;
        --mirror)
            mirror=true
            nextMirror=true
        ;;
        *)
            $nextHost && export LEHOST="$opc" && nextHost=false
            $nextMirror && export LEMIRROR="$opc" && nextMirror=false
            $nextDist && distName="$opc" && nextDist=false
            $nextAll && baseIso="$opc" &&  nextAll=false
            $output && OUTPUT="$opc" && output=false
    esac
done

if (($iso || $clean || $all || $edit) && (! $dist || [ -z "$distName" ])) ||
    !($iso || $clean || $all || $edit); then
    echo "Use: $0 OPTION [SRC_IMAGE] --dist DIST_RELEASE"
    echo "  OPTION:"
    echo "  --clean  Cleaning temporary files and old iso"
    echo "  --iso    Uses old temporary files to generates a new LE iso"
    echo "  --all    Generate a new LE iso using the SRC_IMAGE file of base iso"
    echo "  --edit   Executes the edit scripts using old temporary files"
    echo "  --output Specifies the path to the generated iso file"

    exit 2
fi

loadConf "$PREFIX/conf/$distName/create-iso.conf" $distName
#------------------------------------------------------------------------------
# Check ambient integrity

LOGDIR="$LOGDIR"
LOGFILE="$LOGDIR/$(date +"%y-%m-%d_%T_")`basename "$(echo "$distName")"`_$LEMIRROR.log"
checkUser || exit 1
initFiles || exit 2
checkMountedFS || exit 7
checkOutput "$OUTPUT" || exit 8

#------------------------------------------------------------------------------
# Init routines

if $iso; then
    if ! regenerateManifest | log; then
        log "Error to regenarate manifest file"
        exit 3
    fi
    if ! compressFS | log; then
        log "Error to create squash image"
        exit 4
    fi
    if ! createISO | log; then
        log "Error to create ISO image"
        exit 5
    fi
elif $edit; then
    if ! editDistro $distName | log; then
        log "Error to edit Squash image"
        exit 2
    fi
elif $clean; then
    log "Cleaning temporary directory ..."

    rm -rf "$TMP"/* "$CHROOTDIR" "$CDDIR" "$SQUASHIMAGE" || exit 6
elif $all; then
    replaceIso $distName || exit 6

    if ! extractISO $baseIso | log; then
        log "Error to extract $2"
        exit 1
    fi
    if ! editDistro $distName | log; then
        log "Error to edit Squash image"
        exit 2
    fi
    if ! regenerateManifest | log; then
        log "Error to regenarate manifest file"
        exit 3
    fi
    if ! compressFS | log; then
        log "Error to create squash image"
        exit 4
    fi
    if ! createISO | log; then
        log "Error to create ISO image"
        exit 5
    fi
fi

#/root/teste_ram/rsync.sh

exit 0