#!/bin/zsh
#
# nidifica - script to NEST dyne:bolic in various forms
#
#  * Copyright (C) 2003,2004 Denis "jaromil" Rojo - RASTASOFT.org
#
#  * freely distributed in dyne:bolic GNU/Linux http://dynebolic.org
#
#  * This source code is free software; you can redistribute it and/or
#  * modify it under the terms of the GNU Public License as published 
#  * by the Free Software Foundation; either version 2 of the License,
#  * or (at your option) any later version.
#  *
#  * This source code 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.
#  * Please refer to the GNU Public License for more details.
#  *
#  * You should have received a copy of the GNU Public License along with
#  * this source code; if not, write to:
#  * Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

# dynebol.cfg is allways in the root of the filesystem
# DYNEBOL_CRYPT=encryption algorithm (if there is one, only AES128 supported)


#include <libdyne.sh>
#FILE_ID="\$Id$"
if [ -e /home/jaromil/devel/dynebolic/startup/libdyne.sh ]; then
    source /home/jaromil/devel/dynebolic/startup/libdyne.sh
elif [ -e /lib/libdyne.sh ]; then
    source /lib/libdyne.sh
else
    MSG="necessary library not found: /lib/libdyne.sh is missing"
    echo "[!] $MSG"
    rm -f /var/log/setup/error
    echo "$MSG" > /var/log/setup/error
    exit 1
fi

LODEV=12 # always choose a free one! there are 0-128
NESTNAME="dynebol.nst" # that's the default name, dynebolE.nst is encrypted

report_success() {
# $1 success string
    SUCCESS_FILE=/var/log/setup/success
    MSG=$1
    if [ -z "$MSG" ]; then
	return 0
    fi
    notice "$MSG"
    if [ -e $SUCCESS_FILE ]; then
	rm -f $SUCCESS_FILE
    fi
    echo "$MSG" > $SUCCESS_FILE
    return 1
}

report_error() {
    # $1 error string
    ERROR_FILE=/var/log/setup/error
    MSG=$1
    if [ -z "$MSG" ]; then
	return 0
    fi
    error "$MSG"
    if [ -e $ERROR_FILE ]; then
	rm -f $ERROR_FILE
    fi
    echo "$MSG" > $ERROR_FILE
    return 1
}


############################
### main()
###

notice "nidifica  - create dyne:bolic nest"
act "(c)2003,2004 by jaromil - RASTASOFT.org"
act "invoked with args \"$*\" "
act "running on `date`"

OPTS=`getopt -o hvs:l:e: --long help,version,size:,loc:,encrypt: -n 'nidifica' -- "$@"`

eval set -- "$OPTS"

while true; do
    case "$1" in
	-h)
	    echo " .  nidifica [-hv] [-e -s mbytes] -l location"
	    echo " .  -v, --version print out application info"
	    echo " .  -h, --help    print this small usage guide"
	    echo " .  -e, --encrypt encrypt nest with algo (see man losetup)"
	    echo " .  -s, --size    size of nest in megabytes"
	    echo " .  -l, --loc     target location"
	    exit 2
	    ;;
	-v)
	    exit 2
	    ;;
	-s)
	    SIZE=$2
	    shift 2
	    ;;
	-l)
	    LOCATION=$2
	    shift 2
	    ;;
	-e)
	    ENCRYPT=$2
	    shift 2
	    ;;
	--) shift; break ;;
	*) error "error in given options"; exit 1 ;;
    esac
done

# check presence of all needed parameters
FATAL=0
if [ -z $LOCATION ]; then
    error "must specify location"
    FATAL=1
fi

if [ $FATAL != 0 ]; then
    report_error "nidifica called with wrong arguments, operation aborted."
    sleep 4
    exit 1
fi

if [ $ENCRYPT ]; then
    NESTNAME="dynebolE.nst"
fi

notice "--- nesting to $LOCATION"
sleep 1




    if [ -z "$SIZE" ]; then
	report_error "missing size as argument to nidifica -m nest"
	exit 1
    fi
    
    if [ ! -x $LOCATION ]; then
        report_error "Location $LOCATION does not exist or is not a directory"
	exit 1
    fi

    if [ -e "$LOCATION/${NESTNAME}" ]; then
	echo -n "[?] You want to overwrite the existing nest?"
	getkey 10
	if [ $? != 0 ]; then # getkey returns 1 when no, 2 timeout, 0 yes
	    echo " no"
	    report_error "User aborted operation: should not overwrite existing nest"
	    exit 1
	else
            echo " yes"
	fi
    fi
    

    SIZE_4k=` echo "($SIZE*1000)/4"|bc`
    notice "generating file of ${SIZE}Mb (${SIZE_4k} blocks of 4Kb)"
    act "dd if=/dev/zero of=${LOCATION}/${NESTNAME} bs=4k count=$SIZE_4k"
    echo -n " .  "
    dd if=/dev/zero of=${LOCATION}/${NESTNAME} bs=4k count=${SIZE_4k}
    
    sync

    
   if [ $? -eq 0 -a -e "${LOCATION}/${NESTNAME}" ]; then
	act "OK: `ls -l ${LOCATION}/${NESTNAME}`"
   else
	report_error "Error creating the nest file ${LOCATION}/${NESTNAME} : (dd if=/dev/zero of=${LOCATION}/${NESTNAME} bs=4k count=$SIZE_4k)"
	sleep 4
	exit 1
    fi
    
    notice "mounting loopback device"
    
    if ! [ -z $ENCRYPT ]; then
	# LA MADONNA E' SENZ'ALTRO UNA PUTTANA: NON C'E' ALTERNATIVA ALCUNA!
	# 3 giorni persi a trovare una parentesi { chiusa con una )
	# grazie ALE@INCAL ! ALEEE OOOO 29 feb 2004 //jrml+ale+ganja @ muenchen
	act " .  using ${ENCRYPT} encryption"
	act " .  YOU MUST INSERT YOUR ENCRYPTION PASSPHRASE NOW"
	act " .   =====  CANNOT BE LESS THAN 20 LETTERS! ====="
	sleep 1
	losetup -e "$ENCRYPT" -T /dev/loop/${LODEV} "$LOCATION/${NESTNAME}"
      # here password gets asked twice by the losetup program
      # input from user is taken from stdin
    else
	losetup /dev/loop/${LODEV} "$LOCATION/${NESTNAME}"
    fi




    
    if [ $? = 0 ]; then
	if ! [ -z $ENCRYPT ]; then
	    act "OK, REMEMBER YOUR PASSPHRASE OR YOU WILL LOOSE"
	    act "ALL THE DATA THAT YOU WILL PUT IN THIS NEST !"
		# setup the encryption for the configuration file
		# (it takes all DYNEBOL_ variables, without prefix
		# as new settings) 
	    NEST_CRYPT="$ENCRYPT" #QUAA
	fi
    else
	report_error "Error in mounting nest loopback device : (losetup /dev/loop/${LODEV} $LOCATION/${NESTNAME}) with encryption set to $ENCRYPT"
	rm "$LOCATION/$DYNEBOL_NST"
	sleep 4
	exit 1
    fi
    
    sync
    
    notice "Creating the EXT2 internal filesystem"
    mkfs.ext2  -L "dyne:bolic nest" /dev/loop/${LODEV}
    if [ $? = 0 ]; then
	act "OK, loopback device succesfully formatted"
    else
	losetup -d /dev/loop/${LODEV}
	report_error "Error formatting the nest (mkfs /dev/loop/$LODEV)"
	rm "$LOCATION/$DYNEBOL_NST"
	sleep 4
	exit 1
    fi
    
    sync
    
    notice "Mount the nest and populate it"
    mount -t ext2  /dev/loop/${LODEV} /mnt/nest
    
    echo -n " .  "
    mkdir /mnt/nest/home
    # copy hidden files
    cp -ra /home/.* /mnt/nest/home
    # omit the extras directory 
    for i in `ls /home | grep -v extras`; do
      cp -ra /home/$i /mnt/nest/home
    done
    echo -n "home, "

    cp -ra /etc /mnt/nest
    echo -n "etc, "

    cp -ra /var /mnt/nest
    echo -n "var, "

    mkdir /mnt/nest/tmp
    chmod a+rwt /mnt/nest/tmp
    echo "tmp"
    
    sync
    umount /mnt/nest
    sync
    
    notice "done!"
    
    losetup -d /dev/loop/${LODEV}
    
    sync
    
    act "here is your new dyne:bolic nest:"
    stat "$LOCATION/${NESTNAME}" | tee -a $DYNEBOLIC_LOG
    
    report_success "Dynebolic nest succesfully created in ${LOCATION}/${NESTNAME} :: `file ${LOCATION}/${NESTNAME}|cut -d: -f2` :: CLOSE ALL APPLICATIONS AND REBOOT TO ACTIVATE YOUR NEST!"
    notice "REBOOT TO ACTIVATE YOUR NEW NEST!"


sleep 5
exit 0
