#!/bin/bash

version="2.99 (rewrite before 3.0)"

function print_name {
cat << EOF
                 Hello $(whoami) ($UID) @ $HOSTNAME

    Noyau (french word for kernel) v$version, written by RIQUER Vincent.

     Noyau v$version is aimed to ease the compilation of the Linux kernel.
    Copyright (C) 2005  RIQUER "script.fan" Vincent <script.fan@free.fr>

    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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

EOF
}

function help {
    print_name
    cat << EOF
usage : -z <archive> : unpack archive (tar.gz) and use as sources
        -j <archive> : unpack archive (tar.bz2) and use as sources
        -a <patch(es) : apply patch(es) to sources before compiling them
                        You may specify multiple patches with 
                        -a "patch1 patch2 ..."
                        Hence the double quotes
        --patchargs=<args> : arguments to be passed to patch when applying each
                             patch (default : -p1 -s)
        -c : configure, then build, then install
        -b : build, then install
  -r --deb : build debian package of the kernel
        -m : add modules to a previously installed kernel
        -i : install an already compiled kernel
        -f : don't run make mrproper
        -t <file> : copy bzImage to <file> instead of trying to recognize name
                    from existing files
        -k : use /proc/config.gz instead of /root/saved-config. Falls back on 
             /root/saved-config if CONFIG_IKCONFIG_PROC is not set in your 
             kernel.
        -e <editor> : specify your preferred text editor (you may have to edit
                      the config file for your boot loader (default : \$EDITOR
                      or vim)
        -d <directory> : specify a path for kernel sources (default : 
                         /usr/src/linux). 
        --no-color : disable colored output
        --text : configure using make config
        --menu : configure using make menuconfig
        --x : configure using make xconfig
        --gtk : configure using make gconfig
        -p : don't do anything (for devs and testers) [  these two might  ]
        -v : verbose mode                             [ need some testing ]
        --help : you guessed ;)
EOF
}

# Parsing cli arguments
while getopts "a:bcd:e:fz:ij:kmnprt:v-:" opt ; do
    case $opt in
        a) patches="$OPTARG" ; echo "-a -> Apply patch(es) $patches" ;;
        b) task=comp ; echo "-b -> Compile, install" ;;
        c) task=conf ; echo "-c -> Configure, compile, install" ;;
        d) sources="$OPTARG" ; echo "-d -> Sources : $sources" ;;
        e) EDITOR="$OPTARG" ; echo "-e -> editor : $EDITOR" ;;
        f) noclean=0 ; echo "-f -> don't run mrproper (discouraged on kernels prior to 2.6 unless used together with -m)" ;;
        z) targzball="$OPTARG" ; echo "-g -> unpack $targzball" ;;
        i) task=inst ; echo "-i -> Install" ;;
        j) tarbz2ball="$OPTARG" ; echo "-j -> unpack $tarbz2ball" ;;
        k) use_proc=0; echo "-k -> use /proc/config.gz" ;;
        m) task=mod ; echo "-m -> Add modules" ;;
        n) no_license_notice=0 ;; 
            # Yes, this is a undocumented option
            # to prevent our script from printing
            # its license 2 times when  launched
            # as user and using the su capability

        p) pretend=0 ;
            echo "-p -> Virtual mode : don't do anything, only print what would have been done" ;;
        r) task=deb ; echo "-r -> Build debian package of the kernel" ;;
        t) bzimage="$OPTARG" ; echo "-t $OPTARG -> bzImage => $OPTARG" ;;
        v) verbose=0 ; echo "-v -> Verbose" ;;
        
        -) case $OPTARG in
            no-color) color=0
                echo "--no-color -> black/white output" ;;
            text) compile=config 
                echo "--text -> make config" ;;
            menu) compile=menuconfig
                echo "--menu -> make menuconfig" ;;
            x) compile=xconfig
                echo "--x -> make xconfig" ;;
            gtk) compile=gconfig
                echo "--gtk -> make gconfig" ;;
            deb) task=deb
                echo "--deb -> make-kpkg" ;;
            patchargs=*) patchargs="${OPTARG:10:500}"
                echo "--patchargs=$patchargs -> running patch with options $patchargs" ;;
            help) help
                exit 0 ;;
        esac
    esac
done

if [ $no_license_notice ]; then
    echo "Your UID is $UID, you are $(whoami) on $HOSTNAME"
else
    print_name
fi

# FIXME
echo rewriting not complete
exit 13

# If $EDITOR is set neither by command line option nor environment, default to
# vim <troll> MY preferred text editor... nano is fine too ;) </troll>
## Yam, you'd better use vim ;)
if [[ $EDITOR == "" ]]; then
    EDITOR='vim'
fi
EDITOR="$(which $EDITOR)" \
    || (echo "Couldn't find $EDITOR in your PATH. please use -e or set your EDITOR env variable" ;
        exit 1)

###############################################################################
#                          Function declarations                              #
###############################################################################

############ Basic error handling and display enhacement functions ############
if [ $color ]; then
    # We do not want colored output so we make color a dummy function
    function color {
        :
    }
else
    function color {
        setterm $@
    }
fi

function error {
    echo $'\a'
    color -background red
    cat << EOF


Exit status of the previously executed command wasn't 0. This means there
probably  was  an  error. To  prevent  undesired effects,  I stop  when a
command returns a non-zero status.

Hope you'll be able to resolve the problem, Bye !
EOF
    color -background black
    echo -e "\n"
    exit 1
}

function execute {
    # By using this function as a wrapper, we are able to work in normal, 
    # verbose, or don't-do-anything modes
    if [ $pretend ]; then
        echo -e "\n [not executed] $@"
        read -p "[ press return ]"
    elif [ $verbose ]; then
        echo " + $@"
        bash -c "$@" || error
    else
        bash -c "$@" || error
    fi
}

###### Question asking functions (to ask again if answer not understood #######
function root {
    # asks the user if he wants to start a su session (if $UID != 0)
    read -n 1 -p "Do you want to start a su session now ? [y/n]  "
    echo ""
    case $REPLY in
        'y')
            su -c "$0 -n $args"
            ;;
        'n')
            exit 1
            ;;
        *)
            root
            ;;
    esac
    # If we reach this point, we already reached the end of the script inside
    # su -c
    exit 0
}


