#!/bin/sh
#
#
# Minas Dasygenis, 2016-2025
# http://arch.ece.uowm.gr
#
#
# ====> Usually executed at bigb5
#
# ** Use Only this script - Nothign Else is required **
#
#
# Script that automates the procedure of creating a remastered CPIO tinycore archive
# that can augment the core.gz archive with all these extra packages. 
# With this procedure, you can boot from the local lan (PXE) or from the Internet (IPXE) a diskless machine
# with your configuration.
#
# USAGE: sh $0 [package/packages names]
#
# examples:
#
# $0 pulseaudio openssh tightvnc rdesktop mc Xlibs Xprogs Xfbdev fltk-1.1.10 flwm_topside wbar aterm firefox-ESR Xorg-7.7 getFlash10 xf86-video-ati-dev
# $0 openssh
# or USE THIS SUGGESTED--->
# mkdir -p /zstorage/tmp/tinycorelinuxbuild/$tcoreversion
# export TINY_tcoreversion=7 ; setenv TINY_tcoreversion 7
# /scripts/system/tinycore_Linux/tinycorelinux_build_remaster.sh `cat /scripts/system/tinycore_Linux/disktools.packages`
#
#
#this is the version number
ver=015

if [ ! -z "$TINY_tcoreversion" ] ; then
    tcoreversion=$TINY_tcoreversion
else
    tcoreversion=10
fi

mainpath=/zstorage/tmp/tinycorelinuxbuild




# #### DO NOT CHANGE ANY VARIABLE BELLOW #####
#
# No other variables require modification
#

#Location of our SSH keys to include in the image
authorized_keys=http://vlsi.gr/authorized_keys


print_deps()
{
#if file exists and has a size greater than 0
if [ ! -s "${tmp}/$1.dep" ] ; then
	#we have already fetch it and examined it in this round...we have to skip it
	#return
    wget -q $url/$1.dep -O $tmp/$1.dep
    #if the file does not exist after instructing the wget to fetch it, just return
    if [ ! -s "$tmp/$1.dep" ] ; then
        return 
    fi
fi

#If we are here, we managed to download a new .dep file and we have to examine it

while read line
do
	#the dep file has only lines each for every dependency
	printf "%s " $line
done < $tmp/$1.dep

printf "\n"
}
#end printing dependencies




note="Check number of parameters that are packets to be installed"
if [ $# -eq 0 ] ; then
	echo Mandatory parameter is missing.
	exit 6
fi






# Only the master thread (the first thread) will write its pid here
pidfile=${outputdir}/pid
if [ ! -f "$pidfile" ] ; then
	echo "----------------------------------------------"
	echo "-----DASYGENIS tiny core remaster creator-----"
	echo "-----http://arch.ece.uowm.gr-----------------"
	echo "-----version: $ver ---------------------------"
	echo "----------------------------------------------"
	echo $$ > $pidfile
fi




cwd=`pwd`
fname=`basename $0`

#Only master thread has a TRAP HANDLER. We check the pid file for this
mypid=`cat $pidfile`
if [ $$ -eq "$mypid" ] ; then
	trap 'rm -f $pidfile> /dev/null 2>&1 ; exit' INT TERM EXIT
fi



#
# Variable for MASTER URL package directory
#
#url=http://distro.ibiblio.org/tinycorelinux/5.x/x86/tcz/
#url=http://distro.ibiblio.org/tinycorelinux/6.x/x86/tcz/

#NOTE:
#$url -> points to the directory that will be used in downloading the files
#$kernelver-> this is a tag that will replace the word -KERNEL found in some dependencies, like mtd-KERNEL.tcz
#          -> to locate it for a new version just enter the URL and see the major.minor version in mtd-XXXXXX.tcz
#
# On vi use something like the following if you have a listing of tcz packages with kernel version: %s/4.19.10-tinycore64/KERNEL/g

if [ $tcoreversion -eq 7 ] ; then
	url=http://distro.ibiblio.org/tinycorelinux/7.x/x86/tcz/
	kernelver="4.2.9-tinycore"
	isofile=${url}../release/TinyCore-current.iso
elif [ $tcoreversion -eq 8 ] ; then
	url=http://distro.ibiblio.org/tinycorelinux/8.x/x86/tcz/
	kernelver="4.8.17-tinycore"
	isofile=${url}../release/TinyCore-current.iso
elif [ $tcoreversion -eq 10 ] ; then
	#url=https://distro.ibiblio.org/tinycorelinux/10.x/x86/tcz/
	#isofile=${url}../release/TinyCore-current.iso
	url=https://distro.ibiblio.org/tinycorelinux/10.x/x86_64/tcz/
	isofile=${url}../release/TinyCorePure64-current.iso
	kernelver="4.19.10-tinycore"
elif [ $tcoreversion -eq 11 ] ; then
	url=http://distro.ibiblio.org/tinycorelinux/11.x/x86/tcz/
	kernelver="5.4.3-tinycore"
	isofile=${url}../release/TinyCore-current.iso
elif [ $tcoreversion -eq 12 ] ; then
	url=http://distro.ibiblio.org/tinycorelinux/12.x/x86/tcz/
	kernelver="5.10.3-tinycore"
	isofile=${url}../release/TinyCore-current.iso
elif [ $tcoreversion -eq 14 ] ; then
	url=http://distro.ibiblio.org/tinycorelinux/14.x/x86_64/tcz/
	kernelver="6.1.2-tinycore"
	isofile=${url}../release/TinyCorePure64-current.iso
else
	echo "No information is known about this tinycore version. Please help"
	exit
fi

echo $url | grep -q 64
if [ $? -eq 0 ] ; then
	extrachars0="pure64"
	extrachars1="64"
	kernelver=${kernelver}${extrachars1}
else
	extrachars0=""
	extrachars1=""
fi


# USE absolute pathname here
outputdir=$mainpath/${tcoreversion}${extrachars0}

# Variable to hold the TAGS of the fetched dependencies
# and the packages as a cache
deptags=${outputdir}/deps

if [ ! -w ${deptags} ]; then
	mkdir $deptags || ( echo FAIL at creating ${deptags} ; exit 7 )
fi




tmp=$deptags

if [ $$ -eq "$mypid" ] ; then
	rm ${tmp}/*.log ${tmp}/packf* > /dev/null 2>&1
fi



if [ ! -w "${outputdir}" ] ; then
	echo "ERROR: Directory ${outputdir} is not writable by you or not found."
	echo "I will issue a [ mkdir $outputdir ]. Press any key to continue."
	echo Press any key character and enter to continue
	read junk
	mkdir -v -p "$outputdir"
	echo "We now continue"
fi

cd "$outputdir"

theiso=$(echo "$isofile" | awk -F'/' '{print $NF}')


if [ ! -f "boot/core${extrachars0}.gz" -o ! -f "boot/vmlinuz${extrachars1}" ] ; then
    #we first need to extract the core.gz and vmlinuz
    #this can only be done if 7z is on our system
    which 7z > /dev/null
    if [ $? -eq 0 ] ; then
        if [ ! -f "$theiso" ] ; then
            echo "Downloading $isofile"
            wget -c -q $isofile -O $theiso
            if [ $? -ne 0 ] ; then
                echo "Error at fetching [$isofile] storing at [$theiso]. Please check."
                break
            fi

            
            if [ ! -f "$theiso" ] ; then
                echo "File [$theiso] absent. Please check."
                break
            fi
            #endif tinecore-current exist
        fi

        7z x  "$theiso" boot/core${extrachars0}.gz > /dev/null || ( echo Fail at extraction of boot/core${extrachars0}.gz && exit 3 )
        7z x  "$theiso" boot/vmlinuz${extrachars1} > /dev/null || ( echo Fail at extraction of vmlinuz${extrachars1} && exit 6 )
    else
        echo 7z not found. You must extract manually boot/core${extrachars0}.gz and boot/vmlinuz${extrachars1}
    fi #end if 7z is present
#end if files vmlinuz and core not present 
else
	note="Using boot/vmlinuz${extrachars1} boot/core${extrachars0}.gz from local file system."
fi


echo $1| grep ".tcz" > /dev/null
if [ $? -ne 0 ] ; then
    #the user omitted the tcz extension, lets add it
    master_pack=${1}".tcz"
else
    #note the file that we want to bring
	master_pack=$1
fi


#In case that the generic KERNEL is used then do change it to our kernel version
master_pack=`echo ${master_pack} | sed "s@KERNEL@$kernelver@g"`



echo "     inserting to ${tmp}/packfile to download -> $url${master_pack}"
echo "$url${master_pack}"           >> ${tmp}/packfile
echo "$url${master_pack}.dep"       >> ${tmp}/packfile
echo "$url${master_pack}.md5.txt"   >> ${tmp}/packfile

if [ -z "$master_pack" ] ; then
	echo "Nothing to do. List of master_pack packages to install is empty"
	exit
fi









go=1
while [ $go -eq 1 ]; 
do
# Recursively call ourselves to install each file
#
	for i in `print_deps $master_pack`
	do
		echo "----> DEPENDECY [$i] for master_pack [$master_pack]"
		sh $0 $i
	done
	#We have examined every dependency, we can instruct the while loop to let us go
	go=0
	#done for every dependency 
done


#Perhaps we carry more variables..lets have another run
mypid=`cat $pidfile`
if [ $$ -ne "$mypid" ] ; then
	#every thread except the master thread exits here
	exit
fi


#Here we are only on the master thread
while [ $# -gt 1 ] ; 
do
	#for every command line argument, we call our script again after we have shifted them by one...
	echo "PackagesRemain to Examine: $#"
	shift
	#$0 is the name of the executable (this is not shifted)
	#$1 is the previous $2 variable, that is now $1 and we examine for this, the files and dependencies
	sh $0 $1
done



#Ok we did all our work. Lets build it.
rm $pidfile





note="File with all .dep files -> ${tmp}/packfinal.dep"
note="File with main packages  -> ${tmp}/packfinal.nodep"


echo "Downloading packages at --> ${tmp}"
cd ${tmp}
cat ${tmp}/packfile  | sort | uniq 		> ${tmp}/packfinal
cat ${tmp}/packfinal | grep '.dep' 		> ${tmp}/packfinal.dep
cat ${tmp}/packfinal | grep -v '.dep' 	> ${tmp}/packfinal.nodep

totalpck=`cat ${tmp}/packfinal | grep -v \.dep | grep -v \.txt | grep -v \.md5 |  wc -l`


echo "Please wait while I am downloading (if absent) total number of packages: [$totalpck]"

rc1=0
ccounter=0

random_tcz=`mktemp rootXXXXXXXX`
rm $random_tcz
mkdir $random_tcz

for iurl in `cat ${tmp}/packfinal.nodep ${tmp}/packfinal.dep`
do
    thefile=`echo $iurl | awk -F / '{ print $NF }'`
    echo $thefile | grep -q \.dep
        if [ $? -eq 0 ] ; then continue ; fi
    echo $thefile | grep -q \.txt
        if [ $? -eq 0 ] ; then continue ; fi
    echo $thefile | grep -q md5
        if [ $? -eq 0 ] ; then continue ; fi

    ccounter=`expr $ccounter + 1`

    echo "[$ccounter/$totalpck] FILE: [$thefile] --> "
    if [ -f $thefile ] ; then
        echo "                  FOUND ON LOCAL CACHE. Next file." 
        ln -v $thefile $random_tcz/
        echo " "
        continue
    else
        echo "                  NOT FOUND at `pwd`/${thefile}. WE HAVE TO DOWNLOAD"
        echo " "
    fi

    wget  --append-output=${tmp}/wget.tinycore.nodep.log -c -np -r -nd  $iurl
    if [ $? -ne 0 ] ; then
        echo "      -FAIL_DOWNLOAD"
        sleep 1
        rc1=1
    else
        echo "      +DOWNLOADED: $thefile"
        ln -v $thefile $random_tcz/
    fi
done


echo "DONE DOWNLOADING. 3 Seconds break"

if [ $rc1 -ne 0 ] ; then
 echo "Some files did not download (it is logical for .dep files not to exist, not everything has dependencies). Note that not all verions of tinycorelinux have every package. I tried to download ${tmp}/packfinal, ${tmp}/packfinal.dep ${tmp}/packfinal.nodep but I received [$rc1]. The logfiles are located at: ${tmp}/wget.tinycore.dep.log ${tmp}/wget.tinycore.nodep.log. Please investigate and press a key to continue"

	echo " ===================== Missing Files (not downloaded) "
	missing_list=`cat ${tmp}/*.log | grep -v md5 | grep -v dep | awk '/^--/{split($0,a,"/"); file=a[length(a)]} /404 Not Found/{printf "%s ", file} END{print ""}'`
	for ifile in $missing_list
    do
        filename_without_ext=`echo $ifile | sed 's/.tcz//g'`
        similar_file=`ls ${filename_without_ext}*.tcz 2>/dev/null`
        if [ ! -z "$similar_file" ]; then
            echo "File [$ifile] not found, but we found the [$similar_file]"
        else
            filename_without_multi=`echo $filename_without_ext | sed 's/-multi//g'`
            similar_file2=`ls ${filename_without_multi}*.tcz 2>/dev/null`
            if [ ! -z "$similar_file2" ] ; then
                echo "File [$ifile] not found, but we found the [$similar_file2]"
            else
                echo "File [$ifile] NOT FOUND"
            fi
        fi
    done
	echo " ===================== Missing Files "
	echo " ==== Place them at [`pwd`] and [$tmp/$random_tcz ]  === and Press any key to continue"
	read junk
fi

rm ${tmp}/packfinal					> /dev/null 2>&1
rm ${tmp}/packfinal.nodep			> /dev/null 2>&1
rm ${tmp}/packfinal.dep				> /dev/null 2>&1
rm ${tmp}/packfile					> /dev/null 2>&1
rm ${tmp}/wget.tinycore.dep.log		> /dev/null 2>&1
rm ${tmp}/wget.tinycore.nodep.log 	> /dev/null 2>&1
echo "DONE downloading MASTER_packages and their DEPENDENCIES."

#
# NOTE: In order to autoload modules from the remastered CPIO that we pass allong, we should note that
# the packages are installed with the /opt/bootlocal.sh script which we create bellow
# if this script has typos then it silenty fails. So create this script and run it AS ROOT if 
# you experience problems.
#

if [ "$go" -eq 0 ] ; then
	echo Building remastered...
	#Now that we have bring all packages, lets build the remastered

	cd $outputdir
	randomname=`mktemp rootXXXXXXXX`
	rm $randomname
	mkdir $randomname
	cd $randomname

    echo " "
    echo " "
	echo "==> Building remastered at [ `pwd` ] "
    echo " "
    echo " "
	sleep 3

	#optional is IN the $outputdir/$randonname
	optional=tmp/builtin/optional


	#Here the dirs are relative, because we work on a foreign host
	mkdir -p $optional
	mkdir -p home/tc/.X.d/
	mkdir -p home/tc/.ssh	
    mkdir -p home/tc/.local/bin/
    mkdir -p root/.config/mc/
    cp -v /scripts/system/tinycore_Linux/extra/ini root/.config/mc/
    cp -v /scripts/c/Linux/i386/cksfv   home/tc/.local/bin/
    cp -v /scripts/c/Linux/i386/md5sum  home/tc/.local/bin/
    cp -v /scripts/test.sfv             home/tc/.local/bin/
    cp -v /scripts/test.md5             home/tc/.local/bin/

    # 
    # --Fetch dasygenis scripts
    #
    wget http://vlsi.gr/hdd0.sh -O  home/tc/.local/bin/hdd0.sh && chmod 755 home/tc/.local/bin/hdd0.sh
    wget http://vlsi.gr/hdd1.sh -O  home/tc/.local/bin/hdd1.sh && chmod 755 home/tc/.local/bin/hdd1.sh
    wget http://vlsi.gr/hdd2.sh -O  home/tc/.local/bin/hdd2.sh && chmod 755 home/tc/.local/bin/hdd2.sh
    wget http://vlsi.gr/hdd3.sh -O  home/tc/.local/bin/hdd3.sh && chmod 755 home/tc/.local/bin/hdd3.sh
    wget http://vlsi.gr/hdd4.sh -O  home/tc/.local/bin/hdd4.sh && chmod 755 home/tc/.local/bin/hdd4.sh
    wget http://vlsi.gr/hdd5.sh -O  home/tc/.local/bin/hdd5.sh && chmod 755 home/tc/.local/bin/hdd5.sh

    chmod -R ugo+rx home/tc/.local/bin/

	#opt/tce required for certificates bellow...
	mkdir -p opt/tce/
	#disable visual bell
	echo 'setterm -blength 0' >> home/tc/.bashrc
	wget "$authorized_keys" -O home/tc/.ssh/authorized_keys
	chown -R 1001 home/tc
	mkdir -p opt/home/tc/.X.d/
	chmod 777 $optional home/tc/.X.d/ opt/home/tc/.X.d/
	mv ${tmp}/$random_tcz/*tcz* $optional/
	rmdir ${tmp}/$random_tcz

	mkdir -p tmp
	chmod 777 tmp

	mkdir opt/ssh
	if [ -d /scripts/system/tinycore_Linux/ssh ] ; then
		cp -v /scripts/system/tinycore_Linux/ssh/* opt/ssh
	fi
	# DO not use tmp/tce/optional, the startup script skips it 
	# OLD: opt/tce/optional
	# NEW: tmp/builtin/optional
	
#Lets bring some Academic Certificates on our system
wget -q http://www.terena.org/activities/tcs/repository/TERENA_SSL_CA.pem -O opt/tce/TERENASSLCA.crt
wget -q https://www.terena.org/activities/tcs/repository/UTN-USERFirst-Hardware.pem -O opt/tce/UTN-USERFirst-Hardware.pem 
# wget -q http://arch.ece.uowm.gr/arch.ece.uowm.gr.pem -O opt/tce/arch.ece.uowm.gr.pem 
wget -q http://arch.ece.uowm.gr/ca-bundle.crt -O opt/tce/ca-bundle.crt 

#
#
# ------ Master Local Startup Script, executed automatically
#
#
echo "==> Please, place any script on ${outputdir}/${randomname}/opt"
echo "==> Please, place any .tcz files in `pwd`/$optional/ and press any key to continue" 
echo "==> Please, place any .lst files of what to load on `pwd`/tmp/builtin/"
echo " "
echo "======== Usually we just press enter here ========"
read junk

echo "Moving to onboot.lst file creation"

#Lets create the list of files to load on boot
ls -1 $optional/*.tcz > tmp/builtin/onboot.lst


echo "Moving to shell script creation"

cat >> opt/bootlocal.sh << 'EOM'
#!/bin/sh
version="2026.02.02"

chmod 777 /tmp
echo "Dasygenis Final RunTime Customization in Progress..please wait"
mkdir -p /usr/local/etc/ssh/
cp -v /opt/ssh/* /usr/local/etc/ssh/
chmod -R 700 /usr/local/etc/ssh

#For privilege seperation
mkdir -p /var/empty

#SSH requires a specific user
adduser -D sshd

/usr/bin/sethostname drmdtinycore
echo "Loading Packages. 30 seconds wait"
for ipac in "`ls /tmp/builtin/optional/*.tcz`"
 do
 echo "                       =====> $ipac"
 sudo -u tc /usr/bin/tce-load -i $ipac >> /tmp/tce-load.log 2>&1
done

echo "All packages were installed, ready to move on"
sleep 3


if [ -d /usr/local/etc/ssh ] ; then
	cp -v /opt/ssh/* /usr/local/etc/ssh/
	chmod 0600 /usr/local/etc/ssh/*
fi

if [ -d /etc/ssh ] ; then
	cp -v /opt/ssh/* /etc/ssh/
	chmod 0600 /etc/ssh/*
fi


clear
#echo "I will try to execute: startx"
#sudo -u tc sh -c 'sleep 30 ; startx'   & 
echo "You can do a sudo -s for root prompt #"
echo "Starting SSH login with tc/Minas0000"

if [ ! -f /usr/local/etc/ssh/ssh_host_rsa_key ] ; then
	/usr/local/bin/ssh-keygen -A 
fi


printf "Minas0000\nMinas0000" | passwd tc 
if [ $? -eq 0 ] ; then
	echo "PASSWORD CHANGED"
else
	echo "PASSWORD NOT CHANGED"
fi

#put the certificate back
mkdir -p /usr/local/etc/ssl/certs/
cp /opt/tce/TERENASSLCA.crt /usr/local/etc/ssl/certs/
cp /opt/tce/UTN-USERFirst-Hardware.pem /usr/local/etc/ssl/certs/
# cp /opt/tce/arch.ece.uowm.gr.pem /usr/local/etc/ssl/certs/
ln -s /opt/tce/TERENA_SSL_CA.pem /usr/local/etc/ssl/certs/TERENA_SSL_CA.pem
cat /opt/tce/ca-bundle.crt >  /usr/local/etc/ssl/certs/ca-bundle.crt

# samba config
cat /opt/smb_extra.conf >> /usr/local/etc/samba/smb.conf
sed -i '/\[global\]/a oplocks = yes\nlevel2 oplocks = yes' /usr/local/etc/samba/smb.conf

# Lets enable protocol compatibility for Windows 10
sed '30 a protocol = SMB2' /usr/local/etc/samba/smb.conf > /tmp/smb01 ; mv /tmp/smb01 /usr/local/etc/samba/smb.conf

mkdir -p /usr/local/etc/samba/private/



if [ ! -f /usr/local/etc/ssh/sshd_config ] ; then
	cp -v /opt/ssh_extra.conf /usr/local/etc/ssh/sshd_config
fi

( echo Minas0000; echo Minas0000 ) | smbpasswd -s -a tc

# Lets fire up the SAMBA
/usr/local/etc/init.d/samba start   || /usr/local/sbin/smbd -D || smbd -D 
/usr/local/etc/init.d/openssh start || /usr/local/sbin/sshd || sshd   || chmod -R 700 /usr/local/etc/ssh &&  /usr/local/etc/init.d/openssh restart
echo '192.168.4.190:/i-data/11f9350d/nfs/NAS210 /mnt/b5nas210_500GB nfs rw,tcp,nolock,noauto,noatime,noexec 0  0' >> /etc/fstab
echo '192.168.0.100:/media/usbtank /mnt/usbtank nfs rw,tcp,nolock,noauto,noatime,noexec 0  0' >> /etc/fstab

mkdir -p /mnt/usbtank /mnt/b5nas210_500GB /mnt/sda1 
mkdir -p /root/.config/mc/
echo ' 

[terminal:screen]
up=\\e[A
down=\\e[B
left=\\e[D
right=\\e[C

'			>> /root/.config/mc/ini

killall -USR1  udhcpc || udhcpc -x hostname:diskstation2023 &

EOM

echo 'echo "My Ip drmdtinycore.dyn.vlsi.gr is: "' >> opt/bootlocal.sh
echo 'ifconfig -a' >> opt/bootlocal.sh
echo 'echo "Login User: tc , Password: Minas0000 and then sudo -s"' >> opt/bootlocal.sh
echo 'IP=`ifconfig eth0 | grep inet | sed -E "s@^[^0-9]*([0-9.]*).*@\1@g"`' >> opt/bootlocal.sh
#warning: -o is not supported on 7
echo '(sleep 60 ; export IP=`ifconfig eth0 | grep inet | sed -E "s@^[^0-9]*([0-9.]*).*@\1@g"` ;   wget --no-check-certificate "https://arch.ece.uowm.gr/dyndns/?host=drmdtinycore.dyn.vlsi.gr&addr=${IP}&key=gg1" -O /tmp/dyndns.log ) & ' >> opt/bootlocal.sh
# for 1000Mbps card that may cause a problem in 4X kernel
echo '# In case there is problem to enable the following lines'  >> opt/bootlocal.sh
echo '# ( sleep 30 ; ethtool -s eth0  speed 100 duplex full autoneg on )' >> opt/bootlocal.sh
echo '# ( sleep 40 ; ethtool -K eth0 gso off gro off tso off )' >> opt/bootlocal.sh
echo '# Possible decrease rign buffers: '  >> opt/bootlocal.sh
echo '# ( ethtool -G eth0 rx 80 tx 80 ) ' >> opt/bootlocal.sh

echo 'chown -R tc /home/tc'     >> opt/bootlocal.sh
echo 'chmod -R 755 /home/tc'    >> opt/bootlocal.sh
echo 'cp -v /opt/exports /etc'  >> opt/bootlocal.sh

echo '#Enable it via: /usr/local/etc/init.d/nfs-server start'				    >> opt/exports
echo '#Manually export: exportfs -o rw,fsid=12,no_subtree_check,insecure,crossmnt,no_root_squash *:/mnt' >> opt/exports
echo '#Mount it via: mount -v -o vers=3 drmdtinycore:/mnt /media/nfs/'			>> opt/exports
echo '/mnt *(rw,fsid=12,no_subtree_check,insecure,crossmnt,no_root_squash)'		>> opt/exports
echo "echo BOOTUP SCRIPT FINISHED">> opt/bootlocal.sh

#
# ----- End Master Local Startup Script
#



#
#------- Startup scripts for X windows to home/tc/.X.d/
#
cat > home/tc/.X.d/startup.sh << EOM
#!/bin/sh
# put other system startup commands here

setxkbmap -option "grp:switch,grp:alt_shift_toggle,grp_led:scroll" -layout "us,ro"  &

# firefox -setDefaultBrowser http://arch.ece.uowm.gr &

EOM

#
# --------- End Startup Script
#

#
# ---- startup script for xsession --We overwrite the original with the only exception of removing the waitforX
#
cat > home/tc/.xsession << "EOM"
/usr/local/bin/Xorg -nolisten tcp &
export XPID=$!
sleep 5
"$DESKTOP" 2>/tmp/wm_errors &
export WM_PID=$!
[ -x $HOME/.setbackground ] && $HOME/.setbackground
[ -x $HOME/.mouse_config ] && $HOME/.mouse_config &
[ $(which "$ICONS".sh) ] && ${ICONS}.sh &
[ -d "$HOME/.X.d" ] && find "$HOME/.X.d" -type f -print | while read F; do . "$F"; done

EOM

#
# ---- end startup script for xsession
#


#
#------------------ And do put an rdp script in our system
#
#cat > home/tc/rdp.sh << EOM
#!/bin/sh
#rdesktop -fs -16 83.212.19.243:62220
#EOM
#chmod 755 home/tc/rdp.sh
#
# --------------- END RDP


# Lets append the smb config
mkdir -p usr/local/etc/samba/
cat > opt/smb_extra.conf << EOM

#
# extra config from file opt/smb_extra.conf
#

[mnt]
public = yes
writable = yes
printable = no
create mask = 0777
path = /mnt

[tmp]
public = yes
writable = yes
printable = no
create mask = 0777
path = /tmp

EOM

cat > opt/ssh_extra.conf << EOM
AcceptEnv LANG LC_*
ChallengeResponseAuthentication no
PermitRootLogin yes
PrintMotd no
Subsystem       sftp    /usr/lib/openssh/sftp-server
X11Forwarding yes
PubkeyAuthentication yes
AuthorizedKeysFile .ssh/authorized_keys
EOM


cp home/tc/.X.d/startup.sh opt/home/tc/.X.d/startup.sh
touch home/tc/.X.d/_no_OP_ok


chmod -R 777 home
#ssh wants 700 for tc to work
chmod -R 700 home/tc

chmod 755 opt/bootlocal.sh 
chmod ugo+x home/tc/.X.d/startup.sh opt/home/tc/.X.d/startup.sh
echo opt  > opt/.filetool.lst
echo home > opt/.filetool.lst
chmod 755   opt/.filetool.lst


#
#
# END LOCAL CUSTOMIZATIONS
#
#


echo "......................................."
echo "......................................."
echo "Creating CPIO"

find . | cpio -o -H newc | gzip -2 > ${outputdir}/remaster${tcoreversion}${extrachars0}.gz
if [ $? -eq 0 ] ; then
	echo "File ${outputdir}/remaster${tcoreversion}${extrachars0}.gz created."
	echo "To use it, copy the boot/core${extrachars0}.gz , boot/vmlinuz${extrachars1} and ${outputdir}/remaster${tcoreversion}${extrachars0}.gz to your TFTP (or web bootable location)"
	echo "And use the following PXElinux block"
	echo "----------------------------------"
	echo "label   tinylinux"
	echo "MENU LABEL Tiny Core ${tcoreversion}${extrachars0}"
	echo "kernel vmlinuz"
	echo "append initrd=core.gz,remaster${tcoreversion}${extrachars0}.gz"
	echo "----------------------------------"
	echo "or the following IPXE block"
	echo "( dhcp net0 ; chain http://83.212.19.218/tmp.ipxe )"
	echo "----------------------------------"
	echo '#!ipxe'
	echo 'echo Booting TinyCoreLinux script'
	echo 'set boot-url http://83.212.19.218/nas/'
	echo "kernel ${boot-url}/vmlinuz${extrachars1} showapps vga=791 vga=791 nosplash text verbose multivt tz=GMT+2 pcie_aspm=off"
	echo "initrd ${boot-url}/core${extrachars0}.gz"
	echo "initrd ${boot-url}/remaster"${tcoreversion}${extrachars0}.gz
	echo 'boot || goto failed'
	echo "----------------------------------"

	echo "Files are located for you to copy at: 
	$outputdir/boot/core${extrachars0}.gz
	$outputdir/boot/vmlinuz${extrachars1}
	$outputdir/remaster${tcoreversion}${extrachars0}.gz
	"

else
	echo "Failure at CPIO step. Returned value is not 0"
fi
	echo Cleaning dir ${randomname} in 2 sec
	sleep 2
	cd ${outputdir}
	rm -rf  ${randomname}
	#end for check flag
	rmdir deps > /dev/null 2>&1
fi



