#!/bin/sh
#set -ex

echo ""
echo "************************************"
echo "deprecated, please use make_image.py"
echo "************************************"
echo ""

CONFIGFILE='/etc/sysconfig/cluster/mysql.cf'
[ ! -f $CONFIGFILE ] && { echo "No configfile, exiting" ; exit 1 ; }
starttime=$(date +%s)

hostname=$(hostname | cut -d "." -f 1)

sql_query () {
    echo $* | mysql -s -u ${MYSQL_USER}  -h ${MYSQL_HOST} -p${MYSQL_PASSWD} -D ${MYSQL_DATABASE}
}

print_usage () {
    echo "Usage:"
    echo ""
    echo "  $0 [-v] [-b] [-f] <image_name> [<compression_type>]"
    echo "  [-v]			be verbose"
    echo "  [-b]			build .tar.(gz|bz2|xz) files"
    echo "  [-f]			force being an image-server"
    echo "  [-i]			ignore package errors"
    echo "  [-M]			do not modify image (no chroot calls)"
    echo "  <image_name>		name of image to create"
    echo "  [<compression_type>]	optional; type of compression to use (default: xz)"
    echo "			valid: gz bz2 xz"
    echo
    echo "Possible values for images are: $pimnames"
}

check_buildlock () {
    if [ $build_lock -ne $dev_idx ] && [ $build_lock -gt 0 ] ; then
        lock_name=$(sql_query "SELECT d.name FROM device d WHERE d.device_idx=$build_lock") ;
        echo "Image locked by other image server $lock_name ($build_lock)" ;
        exit -2 ;
    fi
}

set_lock_and_version_and_arch () {
    echo "Updating image and setting build-lock"
    sql_query "UPDATE image SET device=$dev_idx,build_lock=$dev_idx,version=$imversion,\`release\`=$imrelease,builds=$numbuild,build_machine='`hostname -f`',sys_vendor='$1',sys_version='$2',sys_release='$3' WHERE image_idx=$imidx"
    echo "Image $imname has now version $imversion, release $imrelease ($numbuild builds), locked by device `hostname`"
    act_arch=$(sql_query "SELECT architecture FROM image WHERE image_idx=$imidx")
    [ "$act_arch" == "0" ] && sql_query "UPDATE image SET architecture=$4 WHERE image_idx=$imidx"
    debug "Generating versioninfo..."
    echo "VERSION=$imversion.$imrelease" > $imversfile
    echo "BUILDDATE=`date +%c`" >> $imversfile
    echo "IMAGENAME=$imname" >> $imversfile
    echo "BUILDMACHINE=`hostname -f `" >> $imversfile
}

unset_lock () {
    echo "Removing build-lock"
    echo "UPDATE image SET build_lock=0 WHERE image_idx=$imidx"| mysql -u ${MYSQL_USER} -p${MYSQL_PASSWD} -D ${MYSQL_DATABASE} -h ${MYSQL_HOST} ;
}

push_to_imageslaves () {
    net_idx=$(sql_query SELECT n.netdevice_idx FROM netdevice n WHERE n.device=$dev_idx)
    snet_str=""
    for idx in $net_idx ; do
    snet_str="$snet_str OR h.s_netdevice=$idx"
    done
    if [ "${snet_str:-0}" != "0" ] ; then
    snet_str="("${snet_str:4}")"
    server_copied="$server_name+"
    mnt_dir=`mktemp -d /tmp/.mount_XXXXXX`
    sql_query "SELECT d.name, i.ip, h.value, i.alias FROM network nw, network_type nt, netip i INNER JOIN hopcount h INNER JOIN netdevice n INNER JOIN device d INNER JOIN device_config dc INNER JOIN new_config c INNER JOIN device_group dg LEFT JOIN device d2 ON d2.device_idx=dg.device WHERE i.network=nw.network_idx AND nt.network_type_idx=nw.network_type AND i.netdevice=n.netdevice_idx AND d.device_group=dg.device_group_idx AND ( $snet_str ) AND n.netdevice_idx=h.d_netdevice AND n.device=d.device_idx AND (dc.device=d2.device_idx OR dc.device=d.device_idx) AND dc.new_config=c.new_config_idx AND (c.name='image_server') AND nt.identifier='p' ORDER BY h.value, d.name " |
        while read line ; do 
            sname=`echo $line| cut -d " " -f 1`
            mip=`echo $line| cut -d " " -f 2`
            value=`echo $line| cut -d " " -f 3`
            iname=`echo $line| cut -d " " -f 4`
            iname=${iname:-$sname}
            echo $server_copied | grep $sname\+ >/dev/null || {
            echo "Copying image to server $sname (ip $mip, interfacename $iname, cost $value)";
            server_copied="$server_copied $sname+"
            mount -t nfs -v $mip:$imbasedir ${mnt_dir} && {
                rm -rf ${mnt_dir}/${imname}/*
                cp -a $imagedir ${mnt_dir}/.
                umount ${mnt_dir}
                mount $iname:$imversdir ${mnt_dir}
                cp -a $imversfile ${mnt_dir}/.
                umount ${mnt_dir}
                false
            }
            }
        done
        rmdir ${mnt_dir}
    fi
}

print_timestats () {
    rest=$(( $endtime - $starttime ))
    d=$(( $rest / 86400 ))
    rest=$(( $rest - ( $d * 86400 )))
    h=$(( $rest / 3600 ))
    rest=$(( $rest - ( $h * 3600 )))
    m=$(( $rest / 60 ))
    rest=$(( $rest - ( $m * 60 )))

    echo "Took $d d $h h $m m $rest s"
}

. "$CONFIGFILE"

tftpdir=/tftpboot
if [ ! -d $tftpdir ] ; then
    tftpdir=$(ls -d /*/${tftpdir} 2>/dev/null)
    if [ ! -d ${tftpdir:-0} ] ; then
    echo "No tftpdir found"
    exit -1
    fi
fi

echo "Found tftpdir at $tftpdir" 
imbasedir=${tftpdir}/images
imconfig=${imbasedir}/config
imversdir=${imbasedir}/version_control

[ ! -d "$imbasedir" ] && mkdir -p "$imbasedir"

pimnames=$(python-init -c  "from initat.cluster.backbone.models import image ; print ' '.join(image.objects.all().values_list('name', flat=True));")


VERBOSE=0
BUILD=0
FORCE=0
IGNORE_ERRORS=0
MODIFY_IMAGE=1
args=$(getopt vfhbiM $*) || { print_usage ; exit -1 ; }
RED="\033[31m"
GREEN="\033[32m"
YELLOW="\033[33m"
OFF="\033[m"

set -- $args

for i ; do
    case "$i" in
    -v) shift ; VERBOSE=1 ;;
    -b) shift ; BUILD=1 ;;
    -f) shift ; FORCE=1 ;;
    -i) shift ; IGNORE_ERRORS=1 ;;
    -M) shift ; MODIFY_IMAGE=0 ;;
    -h) shift ; print_usage ; exit -1 ;;
    --) shift ; break ;;
    esac
done

if [ $# -gt 0 ] ; then
    imname=$1 ;
    shift ;
else
    echo "Need imagename" ;
    print_usage
    exit -1;
fi
if [ $# -gt 0 ] ; then
    COMPRESSIONTYPE=$1;
    shift;
fi
if [ $# -ne 0 ] ; then
    echo "too many arguments";
    exit -1;
fi

if [ $VERBOSE -gt 0 ] ; then
    debug () { echo $* ; }
    NULL=""
#debug () { logger "`echo $SCRIPTNAME ; echo $*`" ; }
else
    debug () { true ; }
    NULL='> /dev/null'
fi

if [ "$MODIFY_IMAGE" = "1" ] ; then
    check_package_options=""
else
    check_package_options="-M"
fi

bm_stuff=`echo $(sql_query SELECT d.device_idx,d.name FROM device d, device_config dc, new_config c WHERE dc.new_config=c.new_config_idx AND dc.device=d.device_idx AND c.name=\'image_server\' AND d.name=\'$(hostname | cut -d "." -f 1)\')`
if [ "${bm_stuff:-0}" = "0" ] ; then
    if [ "$FORCE" == "0" ] ; then
    echo "${HOSTNAME} is not an image-server"
    exit -1
    else
    dev_idx=1
    server_name="unknown"
    fi
else
    dev_idx=`echo $bm_stuff| cut -d " " -f 1`
    server_name=`echo $bm_stuff| cut -d " " -f 2`
fi

if [ "`echo $COMPRESSIONTYPE | grep gz 2> /dev/null`" ] ; then
    imcomptype='gz'
    tar_flags='-czf'
elif [ "`echo $COMPRESSIONTYPE | grep bz2 2> /dev/null`" ] ; then
    imcomptype='bz2'
    tar_flags='-cjf'
else
    imcomptype='xz'
    tar_flags='-cJf'
    [ ".$COMPRESSIONTYPE" != "." ] && [ "$COMPRESSIONTYPE" != "$imcomptype" ] && echo "Bogus compression type '$COMPRESSIONTYPE', using '$imcomptype'"
fi

stuff=$(python-init -c  "from initat.cluster.backbone.models import image ; print len(image.objects.filter(name='${imname}'));")

#could not get info from image $imname
if [ "${stuff:-0}" = "0" ] ; then
    echo "Wrong image name $imname, possible values are $pimnames." ;
    exit -1 ;
fi

stuff=$(python-init -c  "from initat.cluster.backbone.models import image ; img = image.objects.get(name='${imname}'); print ' '.join([img.source, str(img.version), str(img.release), str(img.builds), str(img.pk), '1' if img.build_lock else '0']);")

imsource="`echo $stuff | cut -d " " -f 1`"
imversion=`echo $stuff | cut -d " " -f 2`
imrelease=`echo $stuff | cut -d " " -f 3`
numbuild=`echo $stuff | cut -d " " -f 4`
imidx=`echo $stuff | cut -d " " -f 5`
build_lock=`echo $stuff | cut -d " " -f 6`
imtype="normal";
imrelease=$(( $imrelease + 1 ))
numbuild=$(( $numbuild + 1 ))

[ ! -d $imsource ] && { echo "No image found at '$imsource' , exiting..."; exit -1 ;}
[ ! -d ${imsource}/bin -o ! -d ${imsource}/sbin ] && { echo "No image found at '$imsource', exiting ..." ; exit -1 ; }

check_buildlock

#if [ "$imtype" = "normal" ] ; then
#    echo "Normal system..."
#else
#    if [ "$imtype" = "rescue" ] ; then
#	echo "Rescue system..."
#	echo "No longer supported"  
#    else
#	echo "Unknown type \"$imtype\", exiting..."
#    fi
#    exit -1
#fi

imagedir=${imbasedir}/${imname}
sysdir=${imagedir}/system

[ ! -d $imagedir ] && mkdir $imagedir
[ ! -d $sysdir ] && mkdir $sysdir
echo "Generating image type $imtype from $imsource to $imagedir ..."


[ ! -d $imversdir ] && mkdir $imversdir
imversfile=${imversdir}/${imname}

debug ""
debug "Actual contents of versionfile:"
[ "$VERBOSE" -eq 1 ] && cat $imversfile
debug ""

rm -rf $sysdir

if [ ! -d $imagedir ] ; then
    debug "Generating imagedir $imagedir..."
    mkdir $imagedir
fi
if [ ! -d $sysdir ] ; then
    debug "Generating sysdir $sysdir..."
    mkdir $sysdir
fi

# check sys_version
if [ -f "${imsource}/etc/fedora-release" ] ; then
    im_type="fedora"
    im_ver="$(cat ${imsource}/etc/fedora-release | tr -s " " | cut -d " " -f 4 )"
    im_rel="0"
elif [ -f "${imsource}/etc/redhat-release" ] ; then
    im_type="redhat"
    cat ${imsource}/etc/redhat-release | grep "Linux WS" > /dev/null && {
    im_ver="3"
    im_rel="0"
    } || {
    im_ver="8"
    im_rel="0"
    }
elif [ -f "${imsource}/etc/debian_version" ] ; then
    im_type="debian"
    im_ver="$(cat ${imsource}/etc/debian_version | cut -d'.' -f 1)"
    im_rel="$(cat ${imsource}/etc/debian_version | cut -d'.' -f 2)"
else
    im_type="suse"
    im_ver="`cat ${imsource}/etc/SuSE-release | grep VERSION | tr -d ' ' | cut -d "=" -f 2 | cut -d "." -f 1`"
    im_rel="`cat ${imsource}/etc/SuSE-release | grep VERSION | tr -d ' ' | cut -d "=" -f 2 | cut -d "." -f 2`"
fi
# check architecture

act_arch=$(file -L ${imsource}/bin/sh | cut -d ":" -f 2 | cut -d "," -f 2 | cut -d " " -f 3)
if [ "$act_arch" = "" ] ; then
    # openSUSE 10.3
    act_arch=$(file -L ${imsource}/bin/sh | cut -d ":" -f 2 | cut -d "," -f 2 | cut -d " " -f 2)
fi
if [ "$act_arch" = "x86-64" ] ; then
    act_arch="x86_64"
elif [ "$act_arch" = "80386" ] ; then
    act_arch="i386"
else
    echo "Cannot parse image_architecture '$act_arch'"
    exit -1
fi
arch_idx=$(sql_query "SELECT architecture_idx FROM architecture WHERE architecture='$act_arch'" | tail -1)

if [ "${arch_idx:-0}" = "0" ] ; then
    sql_query "INSERT INTO architecture SET architecture='$act_arch'"
    arch_idx=$(sql_query "SELECT architecture_idx FROM architecture WHERE architecture='$act_arch'" | tail -1)
fi

echo "Image_vendor is $im_type, Version $im_ver, release $im_rel, image_architecture is $act_arch ($arch_idx)"

set_lock_and_version_and_arch $im_type $im_ver $im_rel $arch_idx

nodir="proc@ media@ sys@"
dlist=""
for dir in $imsource/* ; do
    if [ -d $dir ] && [ ! -L $dir ] ; then
    rdir=`basename $dir`
    echo $nodir | grep ${rdir}@ > /dev/null || {
        dlist="$dlist $rdir" ;
    }
    fi
done

if [ "$BUILD" = "0" ] ; then
    echo -e "\n${RED}**** WARNING. *.bz2-files will not be generated ***${OFF}\n"
fi

/opt/cluster/sbin/check_image_packages.py ${check_package_options} -r $imsource || { [ "${IGNORE_ERRORS}" = "0" ] && { echo "packages missing, exiting..." ; exit -1 ; } }
if [ "$BUILD" = "1" ] ; then
    echo -n "Checking size of system: "
    if [ "$MODIFY_IMAGE" = "1" ] ; then
    chroot $imsource/  ${SHELL} -i -c 'umount proc' 2> /dev/null
    else
    umount ${imsource}/proc
    fi
    debug "-en \n$imsource\t"
    imsource_size=$(du -sk "$imsource/." | cut -d'	' -f1)
    echo "$imsource_size kB"
    test $imsource_size -le 4 && { echo "That is definately too small. Empty dir? Bailing out" ; exit 1 ; }
    echo -n "Checking free diskspace: "
    debug "-en \n$imagedir\t"
    imagedir_space=$(df -k "$imagedir/." | awk '$0 !~ /^Filesystem/{if(/^[[:space:]]/){print($3)}else{print($4);};}')
    echo -n "$imagedir_space kB, which "

    if [ "$imsource_size" -ge "$imagedir_space" ] ; then
    echo "is not enough."
    echo "Please free up some space"
    exit 1
    else
    echo "should be enough"
    fi
	d
# dlist2=""
    flist=`cd "$imsource" ; find ./{,.}* -type d -prune -o -print`


    debug "Directory list:$dlist"
    debug "     File list:$flist"

    cd $sysdir

    echo 
    echo "Copying image:"

    echo "Copying files from slash ..."
    for f in $flist ; do
    cp -a $imsource/$f .
    done
    for dir in $dlist ; do
    echo "Copying dir $dir ..."
    cp -a $imsource/$dir .
    done
    echo

    debug "Copying kernel and kernel modules to "$sysdir"..."

    rm -rf boot/vmlinu* boot/System*
    rm -rf lib/modules/*

    if [ -d ${sysdir}/etc/zypp/repos.d ] ; then
        echo "clearing repo info"
        rm -rf ${sysdir}/etc/zypp/repos.d/*
    fi

    if [ "$MODIFY_IMAGE" = "1" ] ; then
        chroot . depmod -a 2> /dev/null

    if [ "${im_type}" = "suse" ] ; then
        echo "Doing SuSEconfig..."
        rm -f var/run/SuSEconfig-is-running var/lock/SuSEconfig-is-running
        chroot . ${SHELL} -i -c '[ -n "`which SuSEconfig`" ] && SuSEconfig ; umount proc'"$NULL"
    fi

    if [ "$imtype" = "normal" ] ; then
        if [ "${im_type}" = "suse" ] ; then
            debug "Disabling startup YaST call..."
            rm -rf var/adm/setup/ 
            echo "Fixing startup-scripts..."
            chroot . ${SHELL} -c "for file in host-monitoring hoststatus child package-client loadmodules ; do [ -x etc/init.d/\$file ] && /sbin/insserv -d etc/rc.d/\$file ; done"
        elif [ "${im_type}" = "redhat" -o "${im_type}" = "fedora" ] ; then
            echo "Fixing startup-scripts..."
            chroot . ${SHELL} -c "for file in host-monitoring hoststatus child package-client loadmodules ; do [ -x etc/init.d/\$file ] && /sbin/chkconfig \$file on ; done"
        elif [ "${im_type}" = "debian" ] ; then
            echo "Fixing startup-scripts..."
            chroot . ${SHELL} -c "for file in host-monitoring hoststatus child package-client loadmodules ; do [ -x etc/init.d/\$file ] && /usr/sbin/update-rc.d \$file defaults ; done"
        else
            echo "no special fixup known for '${im_type}'."
        fi
    fi
fi
echo
echo "Inserting package information into database "
/opt/cluster/sbin/insert_package_info.py -r $sysdir -i $imidx ${check_package_options} 
else
    echo "Inserting package information into database "
    /opt/cluster/sbin/insert_package_info.py -r $imsource -i $imidx ${check_package_options} 
fi
/opt/cluster/sbin/check_image_packages.py ${check_package_options} -i $imidx || { [ "${IGNORE_ERRORS}" = "0" ] && { echo "packages missing, exiting..." ; exit -1 ; } }


if [ "$BUILD" = "1" ] ; then
    echo "Compressing image..."
    test -f "$imsource/../${imname}.excl" || > $imsource/../${imname}.excl

    size_string=""

    for dir in $dlist ; do
    tarfile=$imagedir/$dir.tar
    bzfile=$imagedir/$dir.tar.$imcomptype
    dirsize=`du -ks $dir | cut -f 1`
    size_string=${size_string}${dir}\;${dirsize}\;
    echo "Compressing $dir ($dirsize k) to new $bzfile "
    rm -f "$bzfile" "$tarfile"*
    if [ "${im_type}" = "debian" ] ; then
        extra_flags="--numeric-owner"
    else
        extra_flags=""
    fi
    (tar -X $imsource/../${imname}.excl $extra_flags $tar_flags $bzfile --preserve-permissions --preserve-order $dir || { echo "Encountered error $?, exiting" ; exit -1 ; }) 2>&1 >&1 | grep -v "socket ignored"
    done

    if test -n "$flist" ; then
    tarfile=$imagedir/slash.tar
    bzfile=$imagedir/slash.tar.$imcomptype
    dirsize=0
    dirsize='$(( '`du -sk $flist | awk '{printf($1" + ")}'`"$dirsize ))"
    eval dirsize=$dirsize
    size_string=${size_string}slash\;${dirsize}\;
    echo "Compressing slash ($dirsize k) to new $bzfile ..."
    rm -f "$bzfile" "$tarfile"*
    tar -X $imsource/../${imname}.excl $tar_flags $bzfile --preserve-permissions --preserve-order $flist || { echo "Encountered error $?, exiting" ; exit -1 ; }
    else
    rm -f $imagedir/slash.tar.$imcomptype
    fi
else
    size_string=""

    for dir in $dlist ; do
    dirsize=`du -ks $imsource/$dir | cut -f 1`
    size_string=${size_string}${dir}\;${dirsize}\;
    done
fi

sql_query "UPDATE image SET size_string='${size_string}', full_build=${BUILD} WHERE image_idx=$imidx"

#fi

#kernelsrcs=''
##this is much, much faster than find /usr/src -type d -name "linux-*" -print
#for d in '' `echo /usr/src/linux-*` ; do
#  test "`echo $d | grep -v 'bak' | grep -v 'oorig'`" && test -d $d && 
#    kernelsrcs="$kernelsrcs $d"
#done
#    tarfile=$imagedir/_kernelsources.tar
#    bzfile=$imagedir/_kernelsources.tar.$imcomptype
#    echo "Compressing kernel-sources to new $bzfile ..."
#    rm -f "$tarfile"*
#    tar -X $imsource/../${imname}.excl $tar_flags $bzfile --preserve-permissions --preserve-order $kernelsrcs

if [ "$BUILD" = "1" ] ; then
    debug "Generating tdir-file for target-dir bits .."
    cp -a $imversfile ${imagedir}/.version
    tdir=`mktemp -d /tmp/tdir_XXXXXX`
    typefile=${imagedir}/.tdir.tar
    for dir in $dlist ; do 
    touch ${tdir}/${dir}
    chmod --reference=$sysdir/$dir ${tdir}/${dir}
    chown --reference=$sysdir/$dir ${tdir}/${dir}
    done
    pushd . > /dev/null
    cd $tdir
    rm -f "$typefile"*

    tar $tar_flags $typefile.$imcomptype *
    cd $imagedir
    rm -rf $tdir
    popd > /dev/null
fi

echo -en ".\nCleaning up.."
rm -rf "$sysdir" && echo "."
echo -en "\nSyncing discs.."
sync && echo ". done"

echo "push_to_imageslaves not implemented, FIXME"
#push_to_imageslaves

unset_lock

endtime=$(date +%s)
print_timestats
