#!/bin/sh
#----------------------------------------------------------------------------------
# /var/install/bin/install-local-package - install package from local harddisk
#
# Creation:     2005-10-03  jed
# Last Update:  $Id$
#
# Copyright (c) 2001-2008 the eisfair team, team(at)eisfair(dot)org
#
# usage: install-local-package
#    or: install-local-package [-keep-all][-no-install] directory-name
#    or: install-local-package [-keep-all][-no-install] index-number of directory
#    or: install-local-package -add-menu
#    or: install-local-package -del-menu
#
# options: -add-menu   - add menu entry to package menu
#          -del-menu   - remove menu entry to package menu
#          -keep-all   - don't delete eis-list.txt and index.txt file(s)
#          -no-install - don't start install script after file generation
#
# 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.
#----------------------------------------------------------------------------------

# read eislib
. /var/install/include/eislib

#exec 2>./install-local-trace-$$.log
#set -x

#------------------------------------------------------------------------------
# check if numeric value
# input : $1 - value
# return:  0 - numeric
#          1 - no numeric
#------------------------------------------------------------------------------
function is_numeric ()
{
    echo "$1"|grep -q '^[0-9]*$'
}

#------------------------------------------------------------------------------
# check if directory is writable
# return:  0 - writable
#          1 - not writable
#------------------------------------------------------------------------------
function is_writeable_dir ()
{
 echo "directory is writable" 2>/dev/null >${pack_dir}/eis-list-writeable.txt
 retcode=$?

 if [ -f ${pack_dir}/eis-list-writeable.txt ]
 then
     rm -f ${pack_dir}/eis-list-writeable.txt
 fi

 return $retcode
}

#----------------------------------------------------------------------------------
# sub: write eislist header
# $1 - page number
#----------------------------------------------------------------------------------
write_eislist_header ()
{
    pnbr=$1

    if [ $pnbr -gt 1 ]
    then
        idxname="-$pnbr"
    else
        idxname=''
    fi

    # write header
    {
        echo "#<comment> Temporary package list"
        echo "#<comment> Copyright (c) 2001-`date +%Y` the eisfair team, team(at)eisfair(dot)org>"
        echo "#<welcome> Page $page_idx of $max_pages - host: `hostname` - directory: $pack_dir"
        echo "#<index> $index_file"
        echo "#<empty>"
        echo "#<message> Available packages:"
    } > ${packlist_dir}/eis-list${idxname}.txt
}

#----------------------------------------------------------------------------------
# sub: write eislist entry
# $1 - page number
#----------------------------------------------------------------------------------
write_eislist_entry ()
{
    pnbr=$1

    if [ $pnbr -gt 1 ]
    then
        idxname="-$pnbr"
    else
        idxname=''
    fi

    if [ $notwritable -eq 1 ]
    then
        # add full path
        FNAME="../..${pack_dir}/$FNAME"
    fi

    echo "#<info 1.1.0> $FNAME" >> ${packlist_dir}/eis-list${idxname}.txt
}

#----------------------------------------------------------------------------------
# sub: write eislist footer
# $1 - page number
#----------------------------------------------------------------------------------
write_eislist_footer ()
{
    pnbr=$1

    if [ $pnbr -gt 1 ]
    then
        idxname="-$pnbr"
    else
        idxname=''
    fi

    # write footer
    {
        echo "#<empty>"

      # if [ $page_idx -gt 1 ]
      # then
      #     echo "#<link> eis-list-`expr $page_idx - 1`.txt <- previous page"
      # fi

        if [ $page_idx -lt $max_pages ]
        then
            echo "#<link> eis-list-`expr $page_idx + 1`.txt -> next page"
        fi
    } >> ${packlist_dir}/eis-list${idxname}.txt
}

#----------------------------------------------------------------------------------
# create eis-list file
#
# input:  $1 - package directory
# return:  0 - ok
#          1 - error accured
#----------------------------------------------------------------------------------
create_eislist ()
{
    rtc=1
    max_per_page=`expr ${_EISLIB_SCREENSIZE_Y} - 10`
    pack_dir="$1"

    if is_writeable_dir "$pack_dir"
    then
        # writable
        notwritable=0
        packlist_dir="$pack_dir"
    else
        # not writable
        notwritable=1
        packlist_dir="/var/tmp"
        mecho -warn "Directory $pack_dir is not writable, hence /var/tmp will be used!"
    fi

    # check if .info-files exist
    ls "$pack_dir"/*.info > /dev/null 2> /dev/null

    if [ $? -eq 0 ]
    then
        # .info-file(s) found!
        cd "$pack_dir"

        max_nbr=`ls *.info|wc -l`
        max_pages=`expr \( $max_nbr - 1 \) \/ $max_per_page + 1`

        # process all .info-files
        nbr_idx=0
        total_idx=0
        page_idx=1
        for FNAME in *.info
        do
            nbr_idx=`expr $nbr_idx + 1`
            total_idx=`expr $total_idx + 1`

            # write header
            if [ $nbr_idx -eq 1 ]
            then
                write_eislist_header $page_idx
            fi

            # write entry
            write_eislist_entry $page_idx

            # write footer
            if [ $nbr_idx -eq $max_per_page -o $total_idx -eq $max_nbr ]
            then
                write_eislist_footer $page_idx

                nbr_idx=0
                page_idx=`expr $page_idx + 1`
            fi
        done

        # save directory to list file
        add_to_dirlist "$pack_dir"

        rtc=0
    fi

    return $rtc
}

#----------------------------------------------------------------------------------
# check directory list file
# $1 - directory to add
#----------------------------------------------------------------------------------
add_to_dirlist ()
{
    dirname="$1"

    if [ -f ${dirlist_file} ]
    then
        # file exist - add to existing file
        last_dirname="`sed -n '1p;1q' $dirlist_file`"

        # add to file if not equal last entry
        cp ${dirlist_file} ${dirlist_file}.tmp

        {
            echo "$dirname"
            grep -v "^${dirname}$" ${dirlist_file}.tmp
        } | sed '11,$d' > ${dirlist_file}

        rm -f ${dirlist_file}.tmp
    else
        # create new file
        echo "$dirname" > ${dirlist_file}
    fi
}

#----------------------------------------------------------------------------------
# show last 10 directory entries
#----------------------------------------------------------------------------------
show_dirlist ()
{
    idx=0

    if [ -f ${dirlist_file} ]
    then
        max_lines=`cat ${dirlist_file} | wc -l`

        if [ $max_lines -gt 1 ]
        then
            # print only if more than one entry
            mecho "Previous selections:"
            mecho

            techo begin 1 3r 2 65

            while read line
            do
                idx=`expr $idx + 1`

                techo row "" $idx "" $line
            done < ${dirlist_file}

            techo end
        fi
    fi
}

#----------------------------------------------------------------------------------
# create index.txt file
#----------------------------------------------------------------------------------
create_index ()
{
    # check if .info-files exist
    ls "$pack_dir"/*.info > /dev/null 2> /dev/null

    if [ $? -eq 0 ]
    then
        # .info-file(s) found!
        cd "$pack_dir"

        # write header
        {
            echo "#------------------------------------------------------------------"
            echo "# $pack_dir/index.txt file generated by $pgmname"
            echo "# Creation date: `date`"
            echo "#------------------------------------------------------------------"
        } > "$packlist_dir/index.txt"

      # techo begin 18 10 12 60

        for FNAME in *.info
        do
            pack_name=`grep "<name>" "$pack_dir/$FNAME" | sed 's#</*name>##g'`
            pack_version=`grep "<version>" "$pack_dir/$FNAME" | sed 's#</*version>##g'`
            pack_status=`grep "<status>" "$pack_dir/$FNAME" | sed 's#</*status>##g'`
            pack_url="file://$pack_dir/$FNAME"

          # techo -file row $pack_name $pack_version $pack_status $pack_url >> $packlist_dir/index.txt
            echo $pack_name $pack_version $pack_status $pack_url >> "$packlist_dir/index.txt"
        done

      # techo end
    fi
}

#==================================================================================
# main
#==================================================================================

dirlist_file=/var/run/install-local-package-list
index_file="http://www.pack-eis.de/index.txt"

pgmname=`basename $0`

# check for EISFAIR_SYSTEM is set, or check it once
if [ -z "${EISFAIR_SYSTEM}" ]
then
    # get eisfair system-type
    . /var/install/include/check-eisfair-version
    # set eisfair system-type
    system_work=${EISFAIR_SYSTEM}
else
    # set eisfair system-type
    system_work=${EISFAIR_SYSTEM}
fi


# read parameters
noask=0
keepall=0
noinstall=0
if [ $# -gt 0 ]
then
    while [ $# -ne 0 -a $noask -eq 0 ]
    do
        case $1 in
            '-add-menu')
                /var/install/bin/add-menu -script "setup.packages.menu" install-local-package "Install (new) package from local directory"
                exit 1
                ;;
            '-del-menu')
                /var/install/bin/del-menu "setup.packages.menu" install-local-package
                exit 1
                ;;
            '-keep-all')
                keepall=1
                shift
                ;;
            '-no-install')
                noinstall=1
                shift
                ;;
            *)
                package_dir="$*"
                noask=1
                ;;
        esac
    done
fi

u_exit=0
until [ $u_exit -eq 1 ]
do
    # read number of entries
    if [ -f $dirlist_file ]
    then
        maxnum=`cat ${dirlist_file} | wc -l`
    else
        maxnum=0
    fi

    if [ $noask -eq 0 ]
    then
        clrhome
        mecho -info "Enter package directory (${system_work})"
        mecho

        # show previous selections
        show_dirlist

        mecho

        if [ $maxnum -ge 1 ]
        then
            preselectstr="`sed -n '1p;1q' $dirlist_file`"
        else
            preselectstr=''
        fi

        # create menu addition
        if [ $maxnum -gt 1 ]
        then
            selectstr=", (1-$maxnum)"
        else
            selectstr=''
        fi

        /var/install/bin/ask "Enter local package directory (absolute path)${selectstr} or (q)uit:" "$preselectstr" '+' > /tmp/ask.$$
        rc=$?
        package_dir="`cat /tmp/ask.$$|sed 's/\/$//'`"
        rm -f /tmp/ask.$$
        if [ $rc = 255 ]
        then
            exit 1
        fi
    fi

    case "$package_dir" in
        [qQ] ) # quit program
            u_exit=1
            ;;
        * ) # go on...
            u_exit=0
            if is_numeric $package_dir
            then
                # numeric value - read from directory list file
                if [ $package_dir -lt 1 -o $package_dir -gt $maxnum ]
                then
                    # error
                    if [ -f $dirlist_file ]
                    then
                        mecho -error "Value out of range!"
                    else
                        mecho -error "Invalid input because no $dirlist_file exists!"
                    fi

                    if [ $noask -eq 0 ]
                    then
                        u_exit=2
                        anykey
                    else
                        # called from command line - exit
                        u_exit=1
                    fi
                else
                    # read from directory list
                    package_dir="`sed -n \"${package_dir}p;${package_dir}q\" $dirlist_file`"
                fi
            fi

            if [ $u_exit -eq 0 ]
            then
                if [ -d "$package_dir" ]
                then
                    # check if it is equal /tmp
                    echo "$package_dir" | grep -q "^/tmp$"

                    if [ $? -ne 0 ]
                    then
                        # not /tmp directory - go on ...
                        if create_eislist "$package_dir"
                        then
                            # create index.txt file
                            create_index

                            if [ $noinstall -eq 0 ]
                            then
                                /var/install/bin/install-package "file://${packlist_dir}/eis-list.txt"
                            fi

                            if [ $keepall -eq 0 ]
                            then
                                mecho
                                /var/install/bin/ask "Keep eis-list*.txt and index.txt files" 'n' > /tmp/ask.$$
                                rc=$?
                                yesno=`cat /tmp/ask.$$`
                                rm -f /tmp/ask.$$
                                if [ $rc = 255 ]
                                then
                                    rm $tmpfile
                                    exit 1
                                fi

                                if [ "$yesno" = "no" ]
                                then
                                    rm -f ${packlist_dir}/eis-list*.txt
                                    rm -f ${packlist_dir}/index.txt
                                fi
                            fi

                            u_exit=1
                        else
                            mecho -error "No .info-files found in $package_dir!"

                            if [ $noask -eq 0 ]
                            then
                                anykey
                            else
                                # exit if called from command line
                                u_exit=1
                            fi
                        fi
                    else
                        mecho -error "Directory '$package_dir' not allowed, choose another one!"

                        if [ $noask -eq 0 ]
                        then
                            anykey
                        else
                            # exit if called from command line
                            u_exit=1
                        fi
                    fi
                else
                    mecho -error "Directory '$package_dir' doesn't exist!"

                    if [ $noask -eq 0 ]
                    then
                        anykey
                    else
                        # exit if called from command line
                        u_exit=1
                    fi
                fi
            fi
            ;;
    esac
done

if [ $keepall -eq 0 ]
then
    mecho
    anykey
fi

#==================================================================================
# end
#==================================================================================