#!/bin/bash

# remastersys script to make an installable livecd/dvd from a Debian installed 
# and customized system
#
#
#  Created by Tony "Fragadelic" Brijeski
#
#  Copyright 2007,2008,2009,2010 Under the GNU GPL2 License
#
#  Originally Created February 12th, 2007
#
#
#
#
#

# checking to make sure script is running with root privileges
. /etc/remastersys/remastersys.version

testroot="`whoami`"

if [ "$testroot" != "root" ]; then
     echo "Usage of remastersys $REMASTERSYSVERSION is as follows:"
     echo " "
     echo "   sudo remastersys backup|clean|dist [cdfs|iso] [filename.iso]"
     echo " "
     echo " "
     echo "Examples:"
     echo " "
     echo "   sudo remastersys backup   (to make a livecd/dvd backup of your system)"
     echo " "
     echo "   sudo remastersys backup custom.iso"
     echo "                             (to make a livecd/dvd backup and call the iso custom.iso)" 
     echo " "
     echo "   sudo remastersys clean    (to clean up temporary files of remastersys)"
     echo " "
     echo "   sudo remastersys dist     (to make a distributable livecd/dvd of your system)"
     echo " "
     echo "   sudo remastersys dist cdfs"
     echo "                             (to make a distributable livecd/dvd filesystem only)"
     echo " "
     echo "   sudo remastersys dist iso custom.iso"
     echo "                             (to make a distributable iso named custom.iso but only"
     echo "                              if the cdfs is already present)"
     echo " "
     echo "   cdfs and iso options should only be used if you wish to modify something on the"
     echo "   cd before the iso is created.  An example of this would be to modify the isolinux"
     echo "   portion of the livecd/dvd"
     echo " "

     exit 1
fi

# load the remastersys.conf file 

. /etc/remastersys.conf

# if the remastersys.conf file is incorrect or missing, make sure to set defaults

#if [ "$LIVEUSER" = "" ]; then
#Somebody must have removed the username from the configuration file
#echo 
#this is a custom live user
#LIVEUSER="custom"
#fi

#make sure live user is all lowercase
#LIVEUSER="`echo $LIVEUSER | awk '{print tolower ($0)}'`"


if [ "$WORKDIR" = "" ]; then
WORKDIR="/home/remastersys/remastersys"
else
WORKDIR="$WORKDIR/remastersys"
fi

if [ "$LIVECDLABEL" = "" ]; then
LIVECDLABEL="Custom Live CD"
fi

#if [ "$CDBOOTTYPE" != "GRUB" ]; then
#CDBOOTTYPE="ISOLINUX"
#fi

if [ "$2" = "cdfs" ]; then
echo "Creating the cd filesystem only"
elif [ "$2" = "iso" ]; then
echo "Creating the iso file only"
elif [ "$2" = "" ]; then
echo " "
else
CUSTOMISO="$2"
fi

if [ "$3" != "" ]; then
CUSTOMISO="$3"
fi

if [ "$CUSTOMISO" = "" ]; then
CUSTOMISO="custom$1.iso"
fi

case $1  in

  backup)
     echo "System Backup Mode Selected"
     ;;

  clean)
     echo "Removing the build directory now..."
     rm -rf $WORKDIR
     echo "Done...Exiting"
     exit 0
     ;;

  dist)
     echo "Distribution Mode Selected"
     ;;


  *)
     echo "Usage of remastersys $REMASTERSYSVERSION is as follows:"
     echo " "
     echo "   sudo remastersys backup|clean|dist [cdfs|iso] [filename.iso]"
     echo " "
     echo " "
     echo "Examples:"
     echo " "
     echo "   sudo remastersys backup   (to make a livecd/dvd backup of your system)"
     echo " "
     echo "   sudo remastersys backup custom.iso"
     echo "                             (to make a livecd/dvd backup and call the iso custom.iso)" 
     echo " "
     echo "   sudo remastersys clean    (to clean up temporary files of remastersys)"
     echo " "
     echo "   sudo remastersys dist     (to make a distributable livecd/dvd of your system)"
     echo " "
     echo "   sudo remastersys dist cdfs"
     echo "                             (to make a distributable livecd/dvd filesystem only)"
     echo " "
     echo "   sudo remastersys dist iso custom.iso"
     echo "                             (to make a distributable iso named custom.iso but only"
     echo "                              if the cdfs is already present)"
     echo " "
     echo "   cdfs and iso options should only be used if you wish to modify something on the"
     echo "   cd before the iso is created.  An example of this would be to modify the isolinux"
     echo "   portion of the livecd/dvd"
     echo " "
     exit 1
     ;;

esac


cdfs (){

# Step 3 - Create the CD tree in $WORKDIR/ISOTMP
echo "Checking if the $WORKDIR folder has been created"
if [ -d "$WORKDIR" ]; then
rm -rf $WORKDIR/dummysys/var/*
rm -rf $WORKDIR/dummysys/etc/*
else
mkdir -p $WORKDIR/ISOTMP/live
mkdir -p $WORKDIR/ISOTMP/isolinux
mkdir -p $WORKDIR/ISOTMP/install
mkdir -p $WORKDIR/ISOTMP/preseed
mkdir -p $WORKDIR/dummysys/dev
mkdir -p $WORKDIR/dummysys/etc/live
mkdir -p $WORKDIR/dummysys/proc
mkdir -p $WORKDIR/dummysys/tmp
mkdir -p $WORKDIR/dummysys/sys
mkdir -p $WORKDIR/dummysys/mnt
mkdir -p $WORKDIR/dummysys/media/cdrom
mkdir -p $WORKDIR/dummysys/var
chmod ug+rwx,o+rwt $WORKDIR/dummysys/tmp

fi




echo "Copying /var and /etc to temp area and excluding extra files"

if [ "$EXCLUDES" != "" ]; then
for addvar in $EXCLUDES ; do
VAREXCLUDES="$VAREXCLUDES --exclude='$addvar' "
done
fi

# if this is kde, copy the adept_notifier_auto.desktop to /etc/remastersys so the installer can put it back as live-initramfs removes it altogether
if [ -f /usr/share/autostart/adept_notifier_auto.desktop ]; then
cp /usr/share/autostart/adept_notifier_auto.desktop /etc/remastersys/
fi

# copy trackerd stuff as live-initramfs disables it
if [ -f /etc/xdg/autostart/tracker-applet.desktop ]; then
cp /etc/xdg/autostart/tracker-applet.desktop /etc/remastersys
fi
if [ -f /etc/xdg/autostart/trackerd.desktop ]; then
cp /etc/xdg/autostart/trackerd.desktop.xdg /etc/remastersys
fi
if [ -f /usr/share/autostart/trackerd.desktop ]; then
cp /usr/share/autostart/trackerd.desktop.share /etc/remastersys
fi



rsync --exclude='*.log.*' --exclude='*.pid' --exclude='*.bak' --exclude='*.[0-9].gz' --exclude='*.deb' $VAREXCLUDES-a /var/. $WORKDIR/dummysys/var/.
rsync $VAREXCLUDES-a /etc/. $WORKDIR/dummysys/etc/.

rm -rf $WORKDIR/dummysys/etc/X11/xorg.conf*
rm -rf $WORKDIR/dummysys/etc/resolv.conf
rm -rf $WORKDIR/dummysys/etc/hosts
rm -rf $WORKDIR/dummysys/etc/hostname
rm -rf $WORKDIR/dummysys/etc/timezone
rm -rf $WORKDIR/dummysys/etc/mtab
rm -rf $WORKDIR/dummysys/etc/fstab
rm -rf $WORKDIR/dummysys/etc/udev/rules.d/70-persistent*
rm -rf $WORKDIR/dummysys/etc/cups/ssl/server.crt
rm -rf $WORKDIR/dummysys/etc/cups/ssl/server.key
rm -rf $WORKDIR/dummysys/etc/ssh/ssh_host_rsa_key
rm -rf $WORKDIR/dummysys/etc/ssh/ssh_host_dsa_key.pub
rm -rf $WORKDIR/dummysys/etc/ssh/ssh_host_dsa_key
rm -rf $WORKDIR/dummysys/etc/ssh/ssh_host_rsa_key.pub
ls $WORKDIR/dummysys/var/lib/apt/lists | grep -v ".gpg" | grep -v "lock" | grep -v "partial" | xargs -i rm $WORKDIR/dummysys/var/lib/apt/lists/{} ; 

if [ "$1" = "dist" ]; then
#fix for buggy debian live setup of gdm and gdm3
sed -i -e '/AutomaticLoginEnable/d' $WORKDIR/dummysys/etc/gdm/gdm.conf
sed -i -e '/AutomaticLoginEnable/d' $WORKDIR/dummysys/etc/gdm3/daemon.conf


echo "  " > $WORKDIR/dummysys/etc/gdm/gdm.conf-custom
rm -rf $WORKDIR/dummysys/etc/group
rm -rf $WORKDIR/dummysys/etc/passwd
rm -rf $WORKDIR/dummysys/etc/shadow
rm -rf $WORKDIR/dummysys/etc/shadow-
rm -rf $WORKDIR/dummysys/etc/gshadow
rm -rf $WORKDIR/dummysys/etc/gshadow-


find $WORKDIR/dummysys/var/run $WORKDIR/dummysys/var/log $WORKDIR/dummysys/var/mail $WORKDIR/dummysys/var/spool $WORKDIR/dummysys/var/lock $WORKDIR/dummysys/var/backups $WORKDIR/dummysys/var/tmp $WORKDIR/dummysys/var/crash -type f -exec rm {} \;

#fix for live scripts setup Contributed by AnthLee of SalineOS
rm -rf $WORKDIR/dummysys/var/lib/live/config/*

for i in dpkg.log lastlog mail.log syslog auth.log daemon.log faillog lpr.log mail.warn user.log boot debug mail.err messages wtmp bootstrap.log dmesg kern.log mail.info
do
        touch $WORKDIR/dummysys/var/log/${i}
done

# remove the non system users on the passwd and group files and copy them to dummysys

# see if any temp users left over from previous versions of remastersys as the process has now changed

grep '^[^:]*:[^:]*:[5-9][0-9][0-9]:' /etc/passwd | awk -F ":" '{print "/usr/sbin/userdel -f",$1}'> $WORKDIR/cleantmpusers
. $WORKDIR/cleantmpusers

grep '^[^:]*:[^:]*:[0-9]:' /etc/passwd >> $WORKDIR/dummysys/etc/passwd
grep '^[^:]*:[^:]*:[0-9][0-9]:' /etc/passwd >> $WORKDIR/dummysys/etc/passwd
grep '^[^:]*:[^:]*:[0-9][0-9][0-9]:' /etc/passwd >> $WORKDIR/dummysys/etc/passwd
grep '^[^:]*:[^:]*:[3-9][0-9][0-9][0-9][0-9]:' /etc/passwd >> $WORKDIR/dummysys/etc/passwd

grep '^[^:]*:[^:]*:[0-9]:' /etc/group >> $WORKDIR/dummysys/etc/group
grep '^[^:]*:[^:]*:[0-9][0-9]:' /etc/group >> $WORKDIR/dummysys/etc/group
grep '^[^:]*:[^:]*:[0-9][0-9][0-9]:' /etc/group >> $WORKDIR/dummysys/etc/group
grep '^[^:]*:[^:]*:[3-9][0-9][0-9][0-9][0-9]:' /etc/group >> $WORKDIR/dummysys/etc/group

grep '^[^:]*:[^:]*:[5-9][0-9][0-9]:' /etc/passwd | awk -F ":" '{print $1}'> $WORKDIR/tmpusers1
grep '^[^:]*:[^:]*:[1-9][0-9][0-9][0-9]:' /etc/passwd | awk -F ":" '{print $1}'> $WORKDIR/tmpusers2
grep '^[^:]*:[^:]*:[1-2][0-9][0-9][0-9][0-9]:' /etc/passwd | awk -F ":" '{print $1}'> $WORKDIR/tmpusers3

cat $WORKDIR/tmpusers1 $WORKDIR/tmpusers2 $WORKDIR/tmpusers3 > $WORKDIR/tmpusers

cat $WORKDIR/tmpusers | while read LINE ;do

echo $LINE | xargs -i sed -e 's/,{}//g' $WORKDIR/dummysys/etc/group > $WORKDIR/dummysys/etc/group.new1
echo $LINE | xargs -i sed -e 's/{},//g' $WORKDIR/dummysys/etc/group.new1 > $WORKDIR/dummysys/etc/group.new2
echo $LINE | xargs -i sed -e 's/{}//g' $WORKDIR/dummysys/etc/group.new2 > $WORKDIR/dummysys/etc/group

rm -rf $WORKDIR/dummysys/etc/group.new1 $WORKDIR/dummysys/etc/group.new2

done

fi

# make sure the adduser and autologin functions of casper as set according to the mode

#[ "$1" = "dist" ] && [ ! -d $WORKDIR/dummysys/home ] && mkdir $WORKDIR/dummysys/home
#[ "$1" = "dist" ] && chmod 755 /usr/share/initramfs-tools/scripts/live-bottom/*adduser /usr/share/initramfs-tools/scripts/live-bottom/*autologin 
#[ "$1" = "backup" ] && [ -d $WORKDIR/dummysys/home ] && rm -rf $WORKDIR/dummysys/home
#[ "$1" = "backup" ] && chmod 644 /usr/share/initramfs-tools/scripts/live-bottom/*adduser /usr/share/initramfs-tools/scripts/live-bottom/*autologin


# copy over some of the necessary stuff for the livecd

if [ -f /etc/remastersys/preseed/*.seed ]; then
cp /etc/remastersys/preseed/* $WORKDIR/ISOTMP/preseed/
fi

#BOOT Type selected is ISOLINUX

#cp /boot/memtest86+.bin $WORKDIR/ISOTMP/isolinux/memtest

#find /usr -name 'isolinux.bin' -exec cp {} $WORKDIR/ISOTMP/isolinux/ \;
#cp /etc/remastersys/install/* $WORKDIR/ISOTMP/install/
if [ `ls /etc/remastersys/customisolinux` ]; then

cp /etc/remastersys/customisolinux/* $WORKDIR/ISOTMP/isolinux/

else

cp /etc/remastersys/isolinux/* $WORKDIR/ISOTMP/isolinux/

sed -i -e 's/__LIVECDLABEL__/'"$LIVECDLABEL"'/g' $WORKDIR/ISOTMP/isolinux/menu.cfg

fi

sleep 1


# Step 4 - Prepare live.conf depending on whether this is a backup or dist

if [ "$1" = "backup" ]; then
LIVEUSER="`grep '^[^:]*:[^:]*:1000:' /etc/passwd | awk -F ":" '{ print $1 }'`"

#fix Thunar volmanrc for live
for i in `ls /home/*`; do

if [ /home/$i/.config/Thunar/volmanrc ]; then
  sed -i -e 's/TRUE/FALSE/g' /home/$i/.config/Thunar/volmanrc
  cp -f /home/$i/.config/volmanrc /root/.config/Thunar/volmanrc
fi

done

fi
if [ ! -d /etc/live ]; then
mkdir -p /etc/live
fi

echo "export LIVE_USERNAME=\"$LIVEUSER\"" > /etc/live/config.conf
echo "export LIVE_USER_FULLNAME=\"Live session user\"" >> /etc/live/config.conf
echo "export LIVE_HOSTNAME=\"$LIVEUSER\"" >> /etc/live/config.conf
if [ "$1" = "backup" ]; then
echo "export LIVE_NOCONFIGS=\"002-user-setup,003-sudo,004-locales,005-tzdata,006-gdm,007-gdm3,008-kdm,009-lxdm,010-nodm,011-slim,015-keyboard-configuration,102-gnome-panel-data,103-gnome-power-manager,104-gnome-screensaver,107-kde-services,116-login\"" >> /etc/live/config.conf
fi



cp /etc/live/config.conf $WORKDIR/dummysys/etc/live/

sleep 1

echo "Setting up live options for $1 mode"

# make a new initial ramdisk including the live scripts
update-initramfs -t -c -k $(uname -r)

echo "Copying your kernel and initrd for the livecd"
cp /boot/vmlinuz-$(uname -r) $WORKDIR/ISOTMP/live/vmlinuz
cp /boot/initrd.img-$(uname -r) $WORKDIR/ISOTMP/live/initrd.img

# Step 5 - Make filesystem.squashfs

if [ -f $WORKDIR/remastersys.log ]; then
rm -f $WORKDIR/remastersys.log
touch $WORKDIR/remastersys.log
fi


if [ -f $WORKDIR/ISOTMP/live/filesystem.squashfs ]; then
rm -f $WORKDIR/ISOTMP/live/filesystem.squashfs
fi

echo "Creating filesystem.squashfs   ... this will take a while so be patient"


SQUASHFSOPTSHIGH="-no-recovery -always-use-fragments -b 1M"


echo "Adding stage 1 files/folders that the livecd requires."

# add the blank folders and trimmed down /var to the cd filesystem

mksquashfs $WORKDIR/dummysys/ $WORKDIR/ISOTMP/live/filesystem.squashfs -no-duplicates -comp xz $SQUASHFSOPTSHIGH 2>>$WORKDIR/remastersys.log

sleep 1

echo "Adding stage 2 files/folders that the livecd requires."

# add the rest of the system depending on the mode selected

if [ "$1" = "backup" ]; then
mksquashfs / $WORKDIR/ISOTMP/live/filesystem.squashfs -no-duplicates -comp xz $SQUASHFSOPTSHIGH -e \
.thumbnails \
.cache \
.bash_history \
Cache \
boot/grub \
dev \
etc \
media \
mnt \
proc \
sys \
tmp \
var \
$WORKDIR $EXCLUDES 2>>$WORKDIR/remastersys.log
#return Thunar volmanrc back to normal
for i in `ls /home/*`; do

if [ /home/$i/.config/Thunar/volmanrc ]; then
  sed -i -e 's/FALSE/TRUE/g' /home/$i/.config/Thunar/volmanrc
  cp -f /home/$i/.config/volmanrc /root/.config/Thunar/volmanrc
fi

done

else
mksquashfs / $WORKDIR/ISOTMP/live/filesystem.squashfs -no-duplicates -comp xz -Xdict-size 100% $SQUASHFSOPTSHIGH -e \
.thumbnails \
.cache \
.bash_history \
Cache \
boot/grub \
dev \
etc \
home \
media \
mnt \
proc \
sys \
tmp \
var \
$WORKDIR $EXCLUDES 2>>$WORKDIR/remastersys.log

fi

sleep 1



#add some stuff the log in case of problems so I can troubleshoot it easier
echo "------------------------------------------------------" >>$WORKDIR/remastersys.log
echo "Mount information" >>$WORKDIR/remastersys.log
mount >>$WORKDIR/remastersys.log
echo "------------------------------------------------------" >>$WORKDIR/remastersys.log
echo "df information" >>$WORKDIR/remastersys.log
df -h >>$WORKDIR/remastersys.log
echo "------------------------------------------------------" >>$WORKDIR/remastersys.log
echo "/etc/remastersys.conf info" >>$WORKDIR/remastersys.log
cat /etc/remastersys.conf >>$WORKDIR/remastersys.log
echo "------------------------------------------------------" >>$WORKDIR/remastersys.log
echo "/etc/live/config.conf info" >>$WORKDIR/remastersys.log
cat /etc/live/config.conf >>$WORKDIR/remastersys.log
echo "------------------------------------------------------" >>$WORKDIR/remastersys.log
echo "/etc/passwd info" >>$WORKDIR/remastersys.log
cat $WORKDIR/dummysys/etc/passwd >>$WORKDIR/remastersys.log
echo "------------------------------------------------------" >>$WORKDIR/remastersys.log
echo "/etc/group info" >>$WORKDIR/remastersys.log
cat $WORKDIR/dummysys/etc/group >>$WORKDIR/remastersys.log
echo "------------------------------------------------------" >>$WORKDIR/remastersys.log
echo "Command-line options = $@" >>$WORKDIR/remastersys.log
echo "------------------------------------------------------" >>$WORKDIR/remastersys.log


sleep 1

#checking the size of the compressed filesystem to ensure it meets the iso9660 spec for a single file" 
SQUASHFSSIZE=`ls -s $WORKDIR/ISOTMP/live/filesystem.squashfs | awk -F " " '{print $1}'`
if [ "$SQUASHFSSIZE" -gt "3999999" ]; then
echo " The compressed filesystem is larger than the iso9660 specification allows for a single file. You must try to reduce the amount of data you are backing up and try again."
echo " The compressed filesystem is larger than the iso9660 specification allows for a single file. You must try to reduce the amount of data you are backing up and try again.">>$WORKDIR/remastersys.log

exit 1
fi


}

iso (){

CREATEISO="`which mkisofs`"
if [ "$CREATEISO" = "" ]; then
CREATEISO="`which genisoimage`"
fi

# check to see if the cd filesystem exists

if [ ! -f "$WORKDIR/ISOTMP/live/filesystem.squashfs" ]; then
echo "The cd filesystem is missing.  Either there was a problem creating the compressed filesystem or you are trying to run sudo remastersys dist iso before sudo remastersys dist cdfs"
echo "The cd filesystem is missing.  Either there was a problem creating the compressed filesystem or you are trying to run sudo remastersys dist iso before sudo remastersys dist cdfs" >>$WORKDIR/remastersys.log

exit 1
fi

#checking the size of the compressed filesystem to ensure it meets the iso9660 spec for a single file" 
SQUASHFSSIZE=`ls -s $WORKDIR/ISOTMP/live/filesystem.squashfs | awk -F " " '{print $1}'`
if [ "$SQUASHFSSIZE" -gt "3999999" ]; then
echo " The compressed filesystem is larger than the iso9660 specification allows for a single file. You must try to reduce the amount of data you are backing up and try again."
echo " The compressed filesystem is larger than the iso9660 specification allows for a single file. You must try to reduce the amount of data you are backing up and try again.">>$WORKDIR/remastersys.log

exit 1
fi



#isolinux mode

sleep 1

# Step 6 - Make the ISO file
echo "Creating $CUSTOMISO in $WORKDIR"
$CREATEISO    \
 -quiet \
 -r    \
 -V "$LIVECDLABEL"    \
 -cache-inodes    \
 -J    \
 -l    \
 -b isolinux/isolinux.bin    \
 -c isolinux/boot.cat    \
 -no-emul-boot    \
 -boot-load-size 4    \
 -boot-info-table    \
 -o $WORKDIR/$CUSTOMISO "$WORKDIR/ISOTMP" 2>>$WORKDIR/remastersys.log 1>>$WORKDIR/remastersys.log

# create hybrid iso so it can be dd installed to a usb flash drive

echo "Making the iso into a hybrid image so it can be imaged to a usb key or burned to optical media"

isohybrid $WORKDIR/$CUSTOMISO

# create the md5 sum file so the user doesn't have to - this is good so the iso file can later be tested to ensure it hasn't become corrupted



echo "Creating $CUSTOMISO.md5 in $WORKDIR"

cd $WORKDIR
md5sum $CUSTOMISO > $CUSTOMISO.md5

sleep 1


echo "$WORKDIR/$CUSTOMISO is ready to be burned or tested in a virtual machine."
echo " "
echo "Check the size and if it is larger than 700MB you will need to burn it to a dvd"
echo " "
ls -hs $WORKDIR/$CUSTOMISO
echo " " 
echo "It is recommended to run 'sudo remastersys clean' once you have burned and tested the $CUSTOMISO"
echo " "


}

# check to see if either iso or cdfs options have been invoked and proceed accordingly

if [ "$2" = "iso" ]; then
iso $@
elif [ "$2" = "cdfs" ]; then
cdfs $@
else
cdfs $@
iso $@
fi




exit 0
