#!/bin/bash

if test $# -lt 3; then echo "Build: You have to set source, version and target!
oscadaBuild {src} {version} {distr}
 Building and placing the result packages and other for the OpenSCADA LTS or Work branches.
 Arguments:
  src     - directory place of the OpenSCADA source code, mostly taken from the repository;
  version - version of the building packages: 0.9.13, 1+rNNNN
  distr   - target distributive: Debian_7_32, ...
 Environments:
  OSCADA_BldOpts   - build options, \"-j2\" by default
  OSCADA_ResTarget - directory for placing the result packages, /mnt/data/share_res/ftp/OpenSCADA
  OSCADA_OptTarget - target options:
   rep - specific build of the repository: enables the packages separation per modules.";
    exit -1
fi

src=$1
version=$2
targ=$3
prefix=/data/oscada
BldDir=$prefix/build
FTPResDir=/data/share_res/ftp
ChrootsDir=$FTPResDir/Misc/chroots
SetArch=
if test "x$OSCADA_BldOpts" = "x"; then OSCADA_BldOpts=-j2; fi

echo "Build: Performing \"$src\" ($version) for $targ."

case $targ in

#***************************************************
#* Source in tarball                               *
#***************************************************
    SrcTar )
	echo "Build: Prepairing the sources tarball to '$OSCADA_ResTarget'."
	#Extracting the building CHROOT
	BldDist=Debian_7_32	#Using that by it contains real lzma, not link to xz
	if test `echo $BldDist | sed -n "/^[^_]*_[^_]*_\([^_]*\)/s//\1/p"` = 32; then SetArch="setarch i586"; fi
	SrcName=`basename $src`
	BldChroot=$BldDir/$BldDist
	if test ! -d $BldChroot; then cd $BldDir; tar xvf $ChrootsDir/$BldDist.tgz > /dev/null; fi
	if test ! -d $BldChroot; then
	    echo "Build: Error extracting the target CHROOT '$BldChroot' from '$ChrootsDir/$BldDist.tgz'."
	    exit -2;
	fi
	#Preparing the source tree
	cp -R $src $BldChroot/root/builder
	if test "x$OSCADA_ResTarget" != "x"; then mount --bind $OSCADA_ResTarget $BldChroot/mnt; fi

	#Same building
	export SrcName
	export SrcVers=$version
	chroot $BldChroot $SetArch /bin/bash << 'EOF'
echo "Build-chroot: SrcName=$SrcName; SrcVers=$SrcVers"
cd /root/builder/$SrcName
ResList="ls *.lzma *.xz"
isLTS=0
if test "#$(echo $SrcVers | sed -n '/^[^.]*.\([^.]*\).*$/s//\1/p')" = "#9"; then isLTS=1; fi
#Creating the result
if test "#$($ResList 2> /dev/null)" = "#"; then
 if test $isLTS != 1; then
  sed -i "s/\[1+r0000\]/\[$SrcVers\]/" configure.ac
  sed -i "s/Version: 1+r0000/Version: $SrcVers/" data/openscada.spec
  sed -i "s/Version: 1+r0000/Version: $SrcVers/" data/openscada_mod_ALT.spec
  sed -i "s/Version: 1+r0000/Version: $SrcVers/" data/openscada_mod_RH.spec
  sed -i "s/1+r0000-1/$SrcVers-1/" data/debian/changelog
  sed -i "s/1+r0000-1/$SrcVers-1/" data/debian_mod/changelog
 fi
 autoreconf -if
 ./configure --enable-AllModuls=dist; make distSrc-xz distRes-xz
fi
#Storing the result
if test "#$($ResList 2> /dev/null)" != "#"; then
 echo "Build-CHROOT: Result list=$($ResList 2> /dev/null)"
 ResDir=/mnt
 # Updating the documentation
 if test $isLTS = 1; then
  rm -R $ResDir/doc; mkdir $ResDir/doc;
  cp -R /root/builder/$SrcName/doc/{en,uk,ru} $ResDir/doc/;
 fi

 ResFiles=$ResDir/SrcTar.files
 if test -f $ResFiles -a "x$(cat $ResFiles)" != "x" -a $isLTS != 1; then
  cd $ResDir;
  rm -f $(cat $ResFiles);
  cd /root/builder/$SrcName;
 fi
 cp -f $($ResList 2> /dev/null) $ResDir
 echo $($ResList 2> /dev/null) > $ResFiles
 touch $ResDir/SrcTar.stamp
fi
EOF
	umount $BldChroot/mnt || exit -3
	#Freeing the building CHROOT
	if test -f $OSCADA_ResTarget/SrcTar.stamp; then rm -R $BldChroot; rm -f $OSCADA_ResTarget/SrcTar.stamp; exit 0; fi
	exit -2
    ;;

#***************************************************
#* Source and binary RPM packages                  *
#***************************************************
    SrcRPM | ALTLinux* | CentOs* | Fedora* | SuSE* | Mandriva* )
	echo "Build: Preparing RPM for '$targ' to '$OSCADA_ResTarget' with options='$OSCADA_OptTarget'."
	export isRep=`echo $OSCADA_OptTarget | sed -n "/.*\(rep\).*/s//\1/p"`
	export isDev=`echo $OSCADA_OptTarget | sed -n "/.*\(dev\).*/s//\1/p"`

	#Extracting the building CHROOT
	BldDist=$targ;
	if test $targ = SrcRPM; then BldDist=CentOs_6_32; fi
	if test `echo $BldDist | sed -n "/^[^_]*_[^_]*_\([^_]*\)/s//\1/p"` = 32; then
	    SetArch="setarch i586"
	    export BuildTarget="--target i586"
	fi
	SrcName=`basename $src`
	BldChroot=$BldDir/$BldDist
	if test ! -d $BldChroot; then
	    cd $BldDir
	    tar xvf $ChrootsDir/$BldDist.tgz > /dev/null
	    cd $BldChroot
	    tar xvf $BldDir/../chroot-data.tgz
	    if test -n "$isDev"; then mount -v --bind /dev $BldChroot/dev; mount -vt devpts devpts $BldChroot/dev/pts; mount -vt proc proc $BldChroot/proc; fi
	fi
	if test ! -d $BldChroot; then
	    echo "Build: Error extracting the target CHROOT '$BldChroot' from '$ChrootsDir/$BldDist.tgz'."
	    exit -2;
	fi
	#Preparing the source tree
	export rpmbuild=/root/rpmbuild
	case $targ in
	    ALTLinux* )	export rpmbuild=/root/RPM ;;
	    SuSE* )	export rpmbuild=/usr/src/packages ;;
	esac
	cp -R $src $BldChroot/$rpmbuild
	if test "x$OSCADA_ResTarget" != "x"; then mount --bind $OSCADA_ResTarget $BldChroot/mnt; fi

	#Same building
	export targ
	export SrcName
	export SrcVers=$version
	chroot $BldChroot $SetArch /bin/bash << 'EOF'
echo "Build-CHROOT: SrcName=$SrcName; SrcVers=$SrcVers"
cd $rpmbuild
ResList="find -type f -name *.rpm"
ResDir=/mnt
isLTS=0
if test "#$(echo $SrcVers | sed -n '/^[^.]*.\([^.]*\).*$/s//\1/p')" = "#9"; then isLTS=1; fi
if test -n "$isRep"; then
 ResDirFin=$ResDir/`echo $targ | sed -n "/^\([^_]*\).*/s//\1/p"`/`echo $targ | sed -n "/^[^_]*_\([^_]*\).*/s//\1/p"`/openscada/SRPMS.main
 if test $targ != SrcRPM; then
  ResDirFin=$ResDir/`echo $targ | sed -n "/^\([^_]*\).*/s//\1/p"`/`echo $targ | sed -n "/^[^_]*_\([^_]*\).*/s//\1/p"`/openscada/RPMS.main
 fi
else
 ResDirFin=$ResDir
 if test $targ != SrcRPM; then
  ResDirFin=$ResDirFin/`echo $targ | sed -n "/^\([^_]*\).*/s//\1/p"`/`echo $targ | sed -n "/^[^_]*_\([^_]*\).*/s//\1/p"`
 fi
fi

#Checking for the Service LTS update
isServLTS=0
if test "#$(echo $SrcVers | sed -n '/^[^.]*.9.[^.]*.\([^.]*\).*$/s//\1/p')" != "#"; then
  ResDirFin=$ResDirFin/service
  isServLTS=1
fi

#Creating the result
if test "#$($ResList)" = "#"; then
 Res1List="ls *$SrcVers*.xz"
 ResFiles=$ResDirFin/RPM_$isLTS.files
 if test $targ != SrcRPM; then ResFiles=$ResDirFin/RPM`echo $targ | sed -n "/^[^_]*_[^_]*_\([^:]*\)/s//\1/p"`_$isLTS.files; fi

 nBuild=`head -n1 $ResFiles | sed -n "/^.*$SrcVers-\([^.]*\)\..*/s//\1/p"`
 nBuild=$[nBuild+1]

 cd $ResDir

 #Getting the source packages if there is no patch present
 if cd $ResDir && test "#$($Res1List 2> /dev/null)" != "#" && test "x$(ls $ResDirFin/openscada_*.patch 2> /dev/null)" = "x"; then
  cp -f $($Res1List 2> /dev/null) $rpmbuild/SOURCES
  cd $rpmbuild/$SrcName
 elif cd $rpmbuild/$SrcName && test "#$($Res1List 2> /dev/null)" = "#"; then
  # Applying the patches
  for iPatch in $(ls $ResDirFin/openscada_*.patch 2> /dev/null); do patch -p0 < $iPatch; done
  # Creating the patched sources
  if test $isLTS != 1; then sed -i "s/\[1+r0000\]/\[$SrcVers\]/" configure.ac; fi
  autoreconf -if
  ./configure --enable-AllModuls=dist; make distSrc-xz distRes-xz
  cp -f $($Res1List 2> /dev/null) ../SOURCES
 fi

 #Getting SPEC
 if test -n "$isRep"; then cp -f data/openscada_mod_ALT.spec ../SPECS/openscada.spec;
 else cp -f data/openscada.spec ../SPECS/openscada.spec; fi

 if test $isLTS != 1; then sed -i "s/Version: 1+r0000/Version: $SrcVers/" ../SPECS/openscada.spec;
 else
  if test $isServLTS = 1; then
   OrigLTS="$(echo $SrcVers | sed -n '/^\([^.]*.9.[^.]*\).*$/s//\1/p')"
   sed -i "s/$OrigLTS/$SrcVers/" ../SPECS/openscada.spec
  fi
  if test -n "$isRep"; then sed -i "s/Name: openscada/Name: openscada_LTS/" ../SPECS/openscada.spec; fi
 fi
 sed -i "s/Release: 1/Release: $nBuild/" ../SPECS/openscada.spec
 sed -i "s/%make$/%make $OSCADA_BldOpts /" ../SPECS/openscada.spec
 sed -i "s/%__make$/%__make $OSCADA_BldOpts /" ../SPECS/openscada.spec

 #Creating RPMs
 if cd $rpmbuild/SOURCES && test "#$($Res1List 2> /dev/null)" != "#"; then
  cd $rpmbuild/SPECS
  if test $targ = SrcRPM; then rpmbuild -bs openscada.spec;
  else rpmbuild -bb $BuildTarget openscada.spec; fi
  cd ..
 fi
fi
#Storing the result
if test "#$($ResList)" != "#"; then
 echo "Build-CHROOT: Placing to '$ResDirFin' for the result $($ResList)"
 if test -f $ResFiles && test "x$(cat $ResFiles)" != "x" && test $isLTS != 1 -o $nBuild != 1 -o $isServLTS = 1; then
  cd $ResDirFin;
  rm -f $(cat $ResFiles);
  cd $rpmbuild;
 fi
 cp -f $($ResList) $ResDirFin
 > $ResFiles
 for i in $($ResList); do echo "$(basename $i)" >> $ResFiles; done
 # Generating the repository meta data
 if test -x $ResDirFin/reposUpdate; then
  echo "Build-CHROOT: Updating the repository for '$ResDirFin'"
  cd $ResDirFin; ./reposUpdate;
 fi
 touch /mnt/RPM.stamp
fi
EOF
	if test -n "$isDev"; then
	    umount $BldChroot/proc || exit -3
	    umount $BldChroot/dev/pts && umount $BldChroot/dev || exit -3
	fi
	umount $BldChroot/mnt || exit -3
	#Freeing the building CHROOT
	if test -f $OSCADA_ResTarget/RPM.stamp; then rm -R $BldChroot; rm -f $OSCADA_ResTarget/RPM.stamp; exit 0; fi
	exit -2
    ;;

#***************************************************
#* Debian binary packages                          *
#***************************************************
    Debian* | Ubuntu* | Raspbian* )
	echo "Build: Preparing Debian for '$targ' to '$OSCADA_ResTarget' with options='$OSCADA_OptTarget'."
	export isRep=`echo $OSCADA_OptTarget | sed -n "/.*\(rep\).*/s//\1/p"`
	#Extracting the building CHROOT
	BldDist=$targ
	BldArch=`echo $BldDist | sed -n "/^[^_]*_[^_]*_\([^_]*\)/s//\1/p"`
	if test $BldArch = 32; then SetArch="setarch i586"; fi
	SrcName=`basename $src`
	BldChroot=$BldDir/$BldDist
	if test ! -d $BldChroot; then
	    cd $BldDir
	    tar xvf $ChrootsDir/$BldDist.tgz > /dev/null
	    cd $BldChroot
	    tar xvf $BldDir/../chroot-data.tgz
	fi
	if test ! -d $BldChroot; then
	    echo "Build: Error extracting the target CHROOT '$BldChroot' from '$ChrootsDir/$BldDist.tgz'."
	    exit -2;
	fi

	#Preparing the source tree
	export debbuild=/root/builder
	cp -R $src $BldChroot/$debbuild

	if test "x$OSCADA_ResTarget" != "x"; then
	    ResDir=$OSCADA_ResTarget/`echo $targ | sed -n "/^\([^_]*\).*/s//\1/p"`/`echo $targ | sed -n "/^[^_]*_\([^_]*\).*/s//\1/p"`
	    if test -n "$isRep"; then ResDir="$ResDir/openscada"; fi
	    mount --bind $ResDir $BldChroot/mnt;
	fi

	#Same building
	export targ
	export BldArch
	export SrcName
	export SrcVers=$version
	chroot $BldChroot $SetArch /bin/bash << 'EOF'
echo "Build-CHROOT: SrcName=$SrcName; SrcVers=$SrcVers; BldArch=$BldArch"
cd $debbuild
ResList="ls *.deb"
ResDir=/mnt
#/`echo $targ | sed -n "/^\([^_]*\).*/s//\1/p"`/`echo $targ | sed -n "/^[^_]*_\([^_]*\).*/s//\1/p"`
#if test -n "$isRep"; then ResDir="$ResDir/openscada"; fi
isLTS=0
if test "#$(echo $SrcVers | sed -n '/^[^.]*.\([^.]*\).*$/s//\1/p')" = "#9"; then isLTS=1; fi
ResFiles=$ResDir/Debian`echo $targ | sed -n "/^[^_]*_[^_]*_\([^:]*\)/s//\1/p"`_$isLTS.files

#Checking for the Service LTS update
isServLTS=0
if test "#$(echo $SrcVers | sed -n '/^[^.]*.9.[^.]*.\([^.]*\).*$/s//\1/p')" != "#"; then
  ResDir=$ResDir/service
  isServLTS=1
fi

nBuild=`head -n1 $ResFiles | sed -n "/^.*$SrcVers-\([^_]*\)_.*/s//\1/p"`
nBuild=$[nBuild+1]

#Creating the result
if test "#$($ResList 2> /dev/null)" = "#"; then
 cd $debbuild/$SrcName

 # Applying the generic patches
 for iPatch in $(ls $ResDir/openscada_*.patch 2> /dev/null); do patch -p0 < $iPatch; done
 # Applying the architecture specific patches
 for iPatch in $(ls $ResDir/openscada-${BldArch}_*.patch 2> /dev/null); do patch -p0 < $iPatch; done

 # Preparing for building
 if test -n "$isRep"; then
  ln -s data/debian_mod debian;
  if test $isLTS = 1; then
   cd debian
   sed -i "s/openscada/openscada-lts/" changelog
   sed -i "s/openscada\([ -]\)/openscada-lts\1/g" control rules
   sed -i "s/openscada$/openscada-lts/g" control
   for iN in $(ls openscada-* 2> /dev/null); do
    mv $iN openscada-lts-$(echo $iN | sed -n '/openscada-\(.*\)/s//\1/p');   #'
   done
   cd ..
  fi
 else ln -s data/debian debian;
 fi
 if test $isLTS != 1; then
  sed -i "s/\[1+r0000\]/\[$SrcVers\]/" configure.ac
  sed -i "s/1+r0000-1/$SrcVers-$nBuild/" debian/changelog
 else
  sed -i "s/$SrcVers-1/$SrcVers-$nBuild/" debian/changelog
  if test $isServLTS = 1; then
   OrigLTS="$(echo $SrcVers | sed -n '/^\([^.]*.9.[^.]*\).*$/s//\1/p')"
   sed -i "s/$OrigLTS/$SrcVers/" debian/changelog
  fi
 fi
 #sed -i "s/\$(MAKE)/\$(MAKE) $OSCADA_BldOpts /" debian/rules

 # Same building
 if test $BldArch = "armhf" -o $BldArch = "arm64"; then
  dpkg-buildpackage -b $OSCADA_BldOpts -a$BldArch -d
 else dpkg-buildpackage -b $OSCADA_BldOpts
 fi

 cd ..
fi

#Storing the result
if test "#$($ResList 2> /dev/null)" != "#"; then
 echo "Build-CHROOT: Placing to '$ResDir' for the result $($ResList)"
 if test -f $ResFiles && test "x$(cat $ResFiles)" != "x" && test $isLTS != 1 -o $nBuild != 1 -o $isServLTS = 1; then
  cd $ResDir;
  rm -f $(cat $ResFiles);
  cd $debbuild;
 fi
 cp -f $($ResList *.dsc *.changes 2> /dev/null) $ResDir
 echo "$($ResList *.dsc *.changes 2> /dev/null)" > $ResFiles
 cd $ResDir
 if test -x ./reposUpdate; then ./reposUpdate; else
    dpkg-scanpackages -m . /dev/null | gzip -9c > ./Packages.gz
 fi
 touch /mnt/Debian.stamp
fi
EOF
	#Freeing the building CHROOT
	umount $BldChroot/mnt || exit -3
	if test -f $ResDir/Debian.stamp; then rm -rf $BldChroot; rm -f $ResDir/Debian.stamp; exit 0; fi
	exit -2
    ;;


#***************************************************
#* Nokia series of debian-based binary packages    *
#***************************************************
    Nokia* )
	echo "Build: Preparing Nokia series of debian-based for '$targ' to '$OSCADA_ResTarget' with options='$OSCADA_OptTarget'."
	#Extracting the building CHROOT
	BldDist=$targ
	SrcName=`basename $src`
	SrcVers=$version
	BldChroot=$BldDir/$BldDist

	if test ! -d $BldChroot; then cd $BldDir; tar xvf $ChrootsDir/$BldDist.tgz > /dev/null; fi
	if test ! -d $BldChroot; then
	    echo "Build: Error extracting the target environment '$BldChroot' from '$ChrootsDir/$BldDist.tgz'."
	    exit -2;
	fi

	#Prepare build tree
	debbuild=$BldChroot/scratchbox/users/roman/home/roman
	ResList="ls *.deb"
	ResDir=$OSCADA_ResTarget/`echo $targ | sed -n "/^\([^_]*\).*/s//\1/p"`/`echo $targ | sed -n "/^[^_]*_\([^_]*\).*/s//\1/p"`
	isLTS=0
	if test "#$(echo $SrcVers | sed -n '/^[^.]*.\([^.]*\).*$/s//\1/p')" = "#9"; then isLTS=1; fi
	if test ! -d $debbuild/$SrcName; then
	    cp -R $src $debbuild
	    chown -R roman:roman $debbuild/$SrcName
	fi

	ResFiles=$ResDir/Debian`echo $targ | sed -n "/^[^_]*_[^_]*_\([^:]*\)/s//\1/p"`_$isLTS.files
	nBuild=`head -n1 $ResFiles | sed -n "/^.*$SrcVers-\([^_]*\)_.*/s//\1/p"`
	nBuild=$[nBuild+1]

	cd $debbuild
	if test "#$($ResList 2> /dev/null)" = "#"; then
	    cd $debbuild/$SrcName

	    # Applying the generic patches
	    for iPatch in $(ls $ResDir/openscada_*.patch 2> /dev/null); do patch -p0 < $iPatch; done

	    # Preparing for building
	    ln -s data/debian debian
	    if test $isLTS != 1; then
		sed -i "s/\[1+r0000\]/\[$SrcVers\]/" configure.ac
		sed -i "s/1+r0000-1/$SrcVers-$nBuild/" debian/changelog
	    else
		sed -i "s/$SrcVers-1/$SrcVers-$nBuild/" debian/changelog
	    fi

	    # Same building
	    $BldChroot/scratchbox/sbin/sbox_ctl start
	    su - roman $BldChroot/scratchbox/login << 'EOF'
cd $(find openscada* -maxdepth 0)
echo "pwd=$(pwd)"
#fakeroot debian/rules binary
dpkg-buildpackage -rfakeroot -b
EOF
	    $BldChroot/scratchbox/sbin/sbox_ctl stop
	    cd ..
	fi

	#Storing the result
	if test "#$($ResList 2> /dev/null)" != "#"; then
	    echo "Build: Placing to '$ResDir' for the result $($ResList)."
	    if test -f $ResFiles && test "x$(cat $ResFiles)" != "x" && test $isLTS != 1 -o $nBuild != 1; then
		cd $ResDir;
		rm -f $(cat $ResFiles);
		cd $debbuild;
	    fi
	    cp -f $($ResList *.dsc *.changes 2> /dev/null) $ResDir
	    echo "$($ResList *.dsc *.changes 2> /dev/null)" > $ResFiles
	    cd $ResDir
	    dpkg-scanpackages -m . /dev/null | gzip -9c > ./Packages.gz

	    # Freeing the building CHROOT
	    rm -R $BldChroot
	    exit 0
	fi

	exit -2
    ;;


#*************************************************************************************************
#* Generic PLC32 and ICP_DAS LP8x81 firmwares based on the ALTLinux builds, by the VPS bldrALT32 *
#*************************************************************************************************
    Gen32PLC* | LP8x81* )
	echo "Build: Preparing the generic PLC32 firmware '$targ' to '$OSCADA_ResTarget' with options='$OSCADA_OptTarget'."

	wVPS=192.168.0.100
	wUser=builder

	#Environments set to file autoBuild.env
	ssh $wUser@$wVPS "echo -e \"targ=$targ\nSrcVers=$version\nwUser=$wUser\nFTPResDir=${OSCADA_ResTarget/$FTPResDir/"/mnt/ftp"}\nOSCADA_OptTarget=$OSCADA_OptTarget\nOSCADA_ResTarget=$OSCADA_ResTarget\" > autoBuild.env"

	#Configuring and build
	ssh $wUser@$wVPS << 'EOF'
. autoBuild.env

isLTS=0
if test "#$(echo $SrcVers | sed -n '/^[^.]*.\([^.]*\).*$/s//\1/p')" = "#9"; then isLTS=1; fi
distALT=`echo $targ | sed -n "/^.*_ALT\(.\)/s//\1/p"`
if test $isLTS = 1; then 
    SrcVersMaj=`echo $SrcVers | sed -n "/\(^[0-9]*.[0-9]*\).*$/s//\1/p"`;
else
    SrcVersMaj=`echo $SrcVers | sed -n "/\(^[0-9]*\).*$/s//\1/p"`;
fi

if test $distALT = 5; then
 ln -fs sources5.list /etc/apt/sources.list
 bldResult="out/desktop/altlinux-5.1-$(date +%Y%m%d)-desktop-i586-ru-plc-cd.flash"
 case $targ in
  Gen32PLC* ) wProf=mkimage-profiles-5-plc; finResult="ALTLinux5"; finResultLnk=$finResult ;;
  LP8x81* )   wProf=mkimage-profiles-5-plc-LP8x81; finResult="LP8x81-ALTLinux5"; finResultLnk=$finResult ;;
 esac
 cd $wProf

 UI=`echo $OSCADA_OptTarget | sed -n "/.*\(UI\).*/s//\1/p"`
 if test "x$UI" = "x"; then
  finResult="$finResult-OpenSCADA_$SrcVers-i586-plc.flash"
  finResultLnk="$finResultLnk-OpenSCADA_$SrcVersMaj-i586-plc.flash"
  if test $isLTS = 1; then ln -fs plcConslLTS profiles/pkg/lists/plc; else ln -fs plcConslWork profiles/pkg/lists/plc; fi
 else
  finResult="$finResult-OpenSCADA_$SrcVers-i586-plcUI.flash"
  finResultLnk="$finResultLnk-OpenSCADA_$SrcVersMaj-i586-plcUI.flash"
  if test $isLTS = 1; then ln -fs plcUILTS profiles/pkg/lists/plc; else ln -fs plcUIWork profiles/pkg/lists/plc; fi
 fi
else
 ln -fs sources6.list /etc/apt/sources.list
 bldResult="out/kdesktop/altlinux-6.0-$(date +%Y%m%d)-kdesktop-i586-en-plc-cd.flash"
 kernel=`echo $OSCADA_OptTarget | sed -n "/.*\(rt1\).*/s//\1/p"`
 case $targ in
  Gen32PLC* )
   wProf=mkimage-profiles-6-plc
   finResult="ALTLinux6"; finResultLnk=$finResult
   if test "x$kernel" = "x"; then kernel=un-def; else kernel=$kernel-up; fi
   ;;
  LP8x81* )
   wProf=mkimage-profiles-6-plc-LP8x81
   finResult="LP8x81-ALTLinux6"; finResultLnk=$finResult
   if test "x$kernel" = "x"; then kernel=rt-up; else kernel=$kernel-up; fi
   ;;
 esac
 cd $wProf

 if test $isLTS = 1; then ln -fs plcLTS.in profiles/pkg/lists/plc.in; else ln -fs plcWork.in profiles/pkg/lists/plc.in; fi

 finResult="$finResult-OpenSCADA_$SrcVers-i586-plc-$kernel.flash"
 finResultLnk="$finResultLnk-OpenSCADA_$SrcVersMaj-i586-plc-$kernel.flash"

 #Reconfiguring for different kernels
 ./configure --with-distro=kdesktop --with-branding=altlinux-kdesktop --with-version=6.0 --with-language=en_US --with-imagetype=flash --with-kernel=$kernel
fi

echo -e "distALT=$distALT\nbldResult=$bldResult\nfinResult=$finResult\nfinResultLnk=$finResultLnk\nFTPResDir=$FTPResDir" >> ~/autoBuild.env

test ! -d ~/$bldResult && make distclean && make plc.cd && make distclean
EOF

#Installation and freeing
	ssh $wUser@$wVPS << 'EOF'
. autoBuild.env

isLTS=0
if test "#$(echo $SrcVers | sed -n '/^[^.]*.\([^.]*\).*$/s//\1/p')" = "#9"; then isLTS=1; fi

if test ! -d $bldResult; then exit; fi
case $targ in
 Gen32PLC* ) finResDirTarg=$FTPResDir/PLC/Generic-X86_32 ;;
 LP8x81* )   finResDirTarg=$FTPResDir/PLC/ICP_DAS-LP8x81 ;;
esac

echo "Build-VPS: Processing and storing the mkimage result from \"$bldResult\" to \"$finResDirTarg\"."
install -d ~/out/$finResult/syslinux/alt0
install -m664 ~/$bldResult/plc ~/out/$finResult
install -m664 ~/$bldResult/live ~/out/$finResult
install -m664 ~/$bldResult/syslinux/alt0/* ~/out/$finResult/syslinux/alt0
if test $distALT = 5; then install -m664 ~/out/syslinuxPLC5.cfg ~/out/$finResult/syslinux/syslinux.cfg
else install -m664 ~/out/syslinuxPLC6.cfg ~/out/$finResult/syslinux/syslinux.cfg; fi
cd ~/out/$finResult; tar cvf ../$finResult.tar ./*

#Removing the previous ones
cd $finResDirTarg
ResFiles=$targ:$OSCADA_OptTarget.files
if test "x$(cat $ResFiles 2> /dev/null)" != "x" -a $isLTS != 1; then rm -f $(cat $ResFiles); fi

#Moving the new ones
echo $finResult.tar > $ResFiles; echo $finResultLnk.tar >> $ResFiles
mv -f ~/out/$finResult.tar ./
ln -sf $finResult.tar $finResultLnk.tar

#Removing the work files
rm -rf ~/out/desktop ~/out/kdesktop ~/out/$finResult

touch $FTPResDir/$targ:$OSCADA_OptTarget.stamp
EOF

	if test -f $OSCADA_ResTarget/$targ:$OSCADA_OptTarget.stamp; then rm -f $OSCADA_ResTarget/$targ:$OSCADA_OptTarget.stamp; exit 0; fi
	exit -2
    ;;


#*****************************************************************
#* Live Disks based on the ALTLinux builds, by the VPS bldrALT32 *
#*****************************************************************
    Live_ALT )
	echo "Build: Preparing '$targ' to '$OSCADA_ResTarget' with options='$OSCADA_OptTarget'."

	wVPS=192.168.0.100
	wUser=builder

	#Setting the environments to the file autoBuild.env
	ssh $wUser@$wVPS "echo -e \"targ=$targ\nSrcVers=$version\nwUser=$wUser\nFTPResDir=${OSCADA_ResTarget/$FTPResDir/"/mnt/ftp"}\nOSCADA_OptTarget=$OSCADA_OptTarget\nOSCADA_ResTarget=$OSCADA_ResTarget\" > autoBuild.env"

	#Configuring and building
	ssh $wUser@$wVPS << 'EOF'
. autoBuild.env

isLTS=0
if test "#$(echo $SrcVers | sed -n '/^[^.]*.\([^.]*\).*$/s//\1/p')" = "#9"; then isLTS=1; fi
image=`echo $OSCADA_OptTarget | sed -n "/.*\(flash\).*/s//\1/p"`
ln -fs sources6.list /etc/apt/sources.list
wProf=mkimage-profiles-6-kdesktop
cd $wProf

if test $isLTS = 1; then ln -fs openscadaLTS profiles/pkg/lists/openscada; else ln -fs openscadaWork profiles/pkg/lists/openscada; fi

if test "x$image" = "x"; then
 image="iso"
 bldResult="out/kdesktop/altlinux-6.0-$(date +%Y%m%d)-kdesktop-i586-en-live-cd.iso"
 finResult="ALTLinux_6-OpenSCADA_$SrcVers-TDE_3.5.13.2-i586-LiveCD_USB.iso"
else
 bldResult="out/kdesktop/altlinux-6.0-$(date +%Y%m%d)-kdesktop-i586-en-live-cd.flash"
 finResult="ALTLinux_6-OpenSCADA_$SrcVers-TDE_3.5.13.2-i586-flash.tar"
fi

#Reconfiguring for different kernels
./configure --with-distro=kdesktop --with-branding=altlinux-kdesktop --with-version=6.0 --with-language=en_US --with-imagetype=$image --with-kernel=un-def

echo -e "image=$image\nbldResult=$bldResult\nfinResult=$finResult\nFTPResDir=$FTPResDir" >> ~/autoBuild.env

test ! -e ~/$bldResult && make distclean && make live-kde3.cd && make distclean
EOF

#Installation and freeing
	ssh $wUser@$wVPS << 'EOF'
. autoBuild.env

isLTS=0
if test "#$(echo $SrcVers | sed -n '/^[^.]*.\([^.]*\).*$/s//\1/p')" = "#9"; then isLTS=1; fi

finResDirTarg=$FTPResDir/Live
if test "$image" = "iso"; then
 if test ! -f $bldResult; then exit; fi
elif test "$image" = "flash"; then
 if test ! -d $bldResult; then exit; fi
 cd $bldResult; tar cvf ~/$bldResult.tar ./*; cd ~
 bldResult=$bldResult.tar
fi

echo "Build-VPS: Processing and storing the mkimage result from \"$bldResult\" to \"$finResDirTarg\"."

#Removing the previous ones
cd $finResDirTarg
ResFiles=$targ:$OSCADA_OptTarget.files
if test "x$(cat $ResFiles 2> /dev/null)" != "x"; then rm -f $(cat $ResFiles); fi
#if test "x$(cat $ResFiles 2> /dev/null)" != "x" -a $isLTS != 1; then rm -f $(cat $ResFiles); fi

#Moving the new ones
echo $finResult > $ResFiles
mv -f ~/$bldResult ./$finResult

md5sum $(ls *.iso *.tar 2> /dev/null) > MD5SUM

#Removing the work files
rm -rf ~/out/kdesktop

touch $FTPResDir/$targ:$OSCADA_OptTarget.stamp
EOF

	if test -f $OSCADA_ResTarget/$targ:$OSCADA_OptTarget.stamp; then rm -f $OSCADA_ResTarget/$targ:$OSCADA_OptTarget.stamp; exit 0; fi

	exit -2
    ;;


#*************************************************************************
#* Live Disks based on the Debian 7-11 builds, by VPS bldrDeb8, or local *
#*************************************************************************
    Live_Deb* )
	echo "Build: Preparing '$targ' to '$OSCADA_ResTarget' with options='$OSCADA_OptTarget'."

	wVPS=localhost
	case $targ in
	    Live_Deb7_* | Live_Deb8_* ) wVPS=192.168.0.101; ;;
	esac

	#Setting the environments to the file autoBuild.env
	ssh root@$wVPS "echo -e \"targ=$targ\nSrcVers=$version\nFTPResDir=${OSCADA_ResTarget/$FTPResDir/"/mnt/ftp"}\nOSCADA_OptTarget=$OSCADA_OptTarget\nOSCADA_ResTarget=$OSCADA_ResTarget\" > autoBuild.env"

	#Configuring and building
	ssh root@$wVPS << 'EOF'
. autoBuild.env

isLTS=0
if test "#$(echo $SrcVers | sed -n '/^[^.]*.\([^.]*\).*$/s//\1/p')" = "#9"; then isLTS=1; fi

RepArch=`echo $targ | sed -n "/^Live_Deb.*_\([^_]*\).*/s//\1/p"`
RepVer=`echo $targ | sed -n "/^Live_Deb\([^_]*\).*/s//\1/p"`
wProf=live$RepVer-$RepArch
case $RepArch in
    32 ) bldResult=live-image-i386.hybrid.iso; finResult=Debian_$RepVer-OpenSCADA_$SrcVers-TDE_R14-i386-LiveCD_USB.iso; ;;
    64 ) bldResult=live-image-amd64.hybrid.iso; finResult=Debian_$RepVer-OpenSCADA_$SrcVers-TDE_R14-amd64-LiveCD_USB.iso; ;;
esac

cd /opt/$wProf

if test $isLTS = 1; then
 cp config/package-lists/=Available=/openscada-lts.list.chroot config/package-lists/openscada.list.chroot;
else cp config/package-lists/=Available=/openscada.list.chroot config/package-lists/openscada.list.chroot;
fi

echo "Build-VPS: LiveBuild profile \"$wProf\" to \"$bldResult\"."

#Cleaning and building
lb clean --purge
lb build

echo "FTPResDir=$FTPResDir"

finResDirTarg=$FTPResDir/Live
if test ! -f $bldResult; then exit; fi

echo "Build-VPS: Processing and storing the LiveBuild result \"$bldResult\" to \"$finResDirTarg\" as \"$finResult\"."

#Removing the previous ones
cd $finResDirTarg
ResFiles=$targ.files
if test "x$(cat $ResFiles 2> /dev/null)" != "x"; then rm -f $(cat $ResFiles); fi
#if test "x$(cat $ResFiles 2> /dev/null)" != "x" -a $isLTS != 1; then rm -f $(cat $ResFiles); fi

#Moving the new ones
echo $finResult > $ResFiles
mv -f /opt/$wProf/$bldResult ./$finResult

md5sum $(ls *.iso *.tar 2> /dev/null) > MD5SUM
touch $FTPResDir/$targ.stamp

#Cleaning the work files
cd /opt/$wProf
lb clean --purge

EOF

	if test -f $OSCADA_ResTarget/$targ.stamp; then rm -f $OSCADA_ResTarget/$targ.stamp; exit 0; fi

	exit -2
    ;;


#*********************************************************
#* ARM tarball packages by the toolchain in VPS bldrDeb8 *
#*********************************************************
    ICP_DAS_LP_ARM | SMH2Gi )
	echo "Build: Preparing ARM by the toolchain '$targ' to '$OSCADA_ResTarget'."

	SrcName=`basename $src`
	wVPS=192.168.0.101

	#Setting the environments to the file /opt/autoBuild.env
	ssh root@$wVPS "echo -e \"targ=$targ\nSrcName=$SrcName\nSrcVers=$version\nFTPResDir=${OSCADA_ResTarget/$FTPResDir/"/mnt/ftp"}\nOSCADA_ResTarget=$OSCADA_ResTarget\" > /opt/autoBuild.env"

	#Configuring and building
	ssh root@$wVPS << 'EOF'
cd /opt
. autoBuild.env
cd $targ
. enter

isLTS=0
if test "#$(echo $SrcVers | sed -n '/^[^.]*.\([^.]*\).*$/s//\1/p')" = "#9"; then isLTS=1; fi	#resRoot=${resRoot}_LTS; fi
resRoot=/opt/$targ/img/root_oscada
finResDirTarg=$FTPResDir/PLC/$targ
finResFile=$targ-OpenSCADA_$SrcVers-root.tgz
finResFileLn=$targ-OpenSCADA-root.tgz

#echo "SrcName=$SrcName; PREFIX=$PREFIX; OSCADA_CFG=$OSCADA_CFG; SrcVers=$SrcVers; FTPResDir=$FTPResDir; finResFile=$finResFile"
if test -d /opt/$SrcName; then rm -Rf /opt/$SrcName; fi
cp -R /mnt/build/$SrcName /opt/$SrcName
cd /opt/$SrcName

# Applying the patches
for iPatch in $(ls $finResDirTarg/openscada_*.patch 2> /dev/null); do patch -p0 < $iPatch; done

# Preseting the actual work version
if test $isLTS != 1; then
  sed -i "s/\[1+r0000\]/\[$SrcVers\]/" configure.ac
fi

autoreconf -ivf
$OSCADA_CFG
make $OSCADA_BldOpts
if test $? = 0; then
 # Pre-cleaning
 rm -f $resRoot/usr/lib/liboscada.so.*
 # Installation
 DESTDIR=$resRoot make install
 rm -rf $resRoot/usr/lib/*.a $resRoot/usr/lib/*.la $resRoot/usr/lib/openscada/*.la $resRoot/usr/include $resRoot/usr/lib/pkgconfig
 $TARGET-strip $resRoot/usr/lib/liboscada.so $resRoot/usr/lib/openscada/*.so
 # Post-cleaning
 rm -f $resRoot/usr/bin/openscada_start
 rm -f $resRoot/etc/{oscada_AGLKS.xml,oscada_Boiler.xml,oscada_start.xml}
 rm -R $resRoot/usr/share/{applications,icons}
 rm -R $resRoot/usr/share/openscada/{AGLKS,Boiler,LibsDB}
 # Packing
 cd $resRoot; tar cvzf $finResFile ./*

 # Removing the previous one
 cd $finResDirTarg
 ResFiles=$targ.files
 if test "x$(cat $ResFiles 2> /dev/null)" != "x" -a $isLTS != 1; then rm -f $(cat $ResFiles); fi

 # Moving the new one
 echo $finResFile > $ResFiles
 mv -f $resRoot/$finResFile ./
 ln -sf $finResFile $finResFileLn

 if test -d /opt/$SrcName; then rm -Rf /opt/$SrcName; fi

 touch $FTPResDir/$targ.stamp
fi
EOF

	if test -f $OSCADA_ResTarget/$targ.stamp; then rm -f $OSCADA_ResTarget/$targ.stamp; exit 0; fi

	exit -2
    ;;
esac

exit -1