#!/bin/bash
###################################################################
#  REMASTERSYS                                                    #
#    Under the GNU GPL2 License                                   #
#    Copyright (C) 2013-2022 Daniel "Nerun" Rodrigues             #
#    Copyright (C) 2007-2012 Tony "Fragadelic" Brijeski           #
#    Full copyright notice: /usr/share/doc/remastersys/copyright  #
###################################################################

# SYSTEM LOCALIZATION
# Target to file:
# /usr/share/locale/(language code)/LC_MESSAGES/remastersys-gui.mo
TEXTDOMAIN=remastersys-gui

# Load version file and settings
. /etc/remastersys/remastersys.version
. /etc/remastersys.conf

Pick=$"Pick"
Info=$"Info"
Yes=$"Yes"
No=$"No"
Quit=$"Quit"

# NOTE: attribute --fixed do not allows to use --width or --height
DIALOGMENU="`which yad` --window-icon=/usr/share/icons/hicolor/16x16/apps/remastersys.png --width=750 --center"
DIALOG="`which yad` --window-icon=/usr/share/icons/hicolor/16x16/apps/remastersys.png --center --fixed"
TITLE="--always-print-result --dialog-sep --image=/usr/share/icons/hicolor/48x48/apps/remastersys.png --title="
TEXT="--text="
ENTRY="--entry "
ENTRYTEXT="--entry-text "
FILESELECTION="--file "
MENU="--list --column=$Pick --column=$Info"
YESNO=" --button=$Yes:0 --button=$No:1 "
MSGBOX=" --button=Ok:0 "
TITLETEXT="Remastersys"

# check if running with root privileges
if [ $(whoami) != "root" ]; then
    $DIALOG $TITLE"$TITLETEXT" $MSGBOX $TEXT$"ERROR: This script must run as superuser. Try with \"sudo\"."
    exit 1
fi

Choose=$"Choose what you want to do:"

BackupString=$"Creates a full system backup including user files."
DistString=$"Creates a distribution on Live CD/DVD: creating both file system (CDFS) and image (ISO)."
DistCDFSString=$"Creates only the file system (CDFS) of a Live CD: designed to add extra files to CD."
DistISOString=$"Creates only the ISO of a Live CD: designed to be used after using the DistCDFS option."
DistBootString=$"Selects a background image for the Live CD/DVD boot menu."
DistGrubString=$"Selects a background image for the GRUB bootloader."
DistSkelString=$"Makes the current user's custom settings the default Live CD/DVD system settings."
ClearSkelString=$"Clears /etc/skel settings to remove all customizations."
ClearString=$"Clears Remastersys working folder."
SettingsString=$"Modify Remastersys settings."
LogString=$"View the Remastersys log file."
AboutString=$"Displays information about Remastersys."

ClearSkel=$"ClearSkel"
Clear=$"Clear"
Settings=$"Settings"
About=$"About"

NoFileSelected=$"You didn't select any file.\n\nClick OK to continue."

mainmenu() {
    CHOICES=`$DIALOGMENU $TITLE"$TITLETEXT" --height=400 --button=Ok:0 --button="$Quit":1 $MENU $TEXT"$Choose" \
    Backup "$BackupString" \
    Dist "$DistString" \
    DistCDFS "$DistCDFSString" \
    DistISO "$DistISOString" \
    DistBoot "$DistBootString" \
    DistGrub "$DistGrubString" \
    DistSkel "$DistSkelString" \
    "$ClearSkel" "$ClearSkelString" \
    "$Clear" "$ClearString" \
    "$Settings" "$SettingsString" \
    Log "$LogString" \
    "$About" "$AboutString"`

    if [ "$?" = "0" ]; then
        CHOICE=$(echo $CHOICES | cut -d "|" -f 1)
    else
        exit 0
    fi

    if [ "$CHOICE" = "Backup" ]; then
        backupmenu
    elif [ "$CHOICE" = "Dist" ]; then
        distmenu
    elif [ "$CHOICE" = "DistCDFS" ]; then
        distcdfsmenu
    elif [ "$CHOICE" = "DistISO" ]; then
        distisomenu
    elif [ "$CHOICE" = "DistBoot" ]; then
        distbootmenu
    elif [ "$CHOICE" = "DistGrub" ]; then
        distgrubmenu
    elif [ "$CHOICE" = "DistSkel" ]; then
        distskelmenu
    elif [ "$CHOICE" = "$ClearSkel" ]; then
        sudo remastersys-skelcopy clear
        $DIALOG $TITLE"$TITLETEXT" $MSGBOX $TEXT$"Configuration files in /etc/skel have been deleted."
        mainmenu
    elif [ "$CHOICE" = "$Clear" ]; then
        cleanmenu
    elif [ "$CHOICE" = "$Settings" ]; then
        modifymenu
    elif [ "$CHOICE" = "Log" ]; then
        if [ -f "$WORKDIR/remastersys.log" ]; then
            $DIALOG $TITLE"$TITLETEXT" --width=750 --height=400 --text-info --filename="$WORKDIR/remastersys.log"
        else
            $DIALOG $TITLE"$TITLETEXT" $MSGBOX $TEXT$"The remastersys.log file does not exist."
        fi

        mainmenu

    elif [ "$CHOICE" = "$About" ]; then
        $DIALOG $TITLE"$TITLETEXT" --center $MSGBOX $TEXT$"Remastersys version $VERSION.\n\n\
This is a graphical user interface created in YAD for Remastersys: a\n\
command-line tool that turns an installed Debian system into a distribution on\n\
Live CD or DVD. It can also be used as a full backup tool that includes /home\n\
folder and all users data.\n\n\
Maintained by Daniel 'Nerun' Rodrigues.\n\n\
Fork of Tony Brijeski's Remastersys (discontinued).\n\n\
Visit <a href=\"https://github.com/nerun/remastersys\">https://github.com/nerun/remastersys</a> for more information."
        mainmenu
    else
        exit 0
    fi
}

# Common procedure to backupmenu(), distmenu(), distcdfsmenu() e distisomenu().
SquashfsSizeCheckup(){
    SQUASHFSSIZE=$(ls -s $WORKDIR/ISOTMP/live/filesystem.squashfs | awk -F " " '{print $1}')
    
    if [ "$SQUASHFSSIZE" -gt "3999999" ]; then
        $DIALOG $TITLE"$TITLETEXT" $MSGBOX $TEXT$"The compressed file system is larger than the ISO 9660 specification allows for\na single file.\n\nYou must try to reduce the amount of data you are backing up and try again."
        exit 1
    fi
}

# Common procedure to backupmenu(), distmenu() e distisomenu().
FilesReady(){
    $DIALOG $TITLE"$TITLETEXT" $MSGBOX $TEXT$"Your $CUSTOMISO and $CUSTOMISO.md5 files are ready in $WORKDIR. It\nis recommended to test it in a virtual machine or on a rewritable CD/DVD to\nensure it works as desired.\n\nClick on OK to return to the main menu."
    mainmenu
}

backupmenu() {
    $DIALOG $TITLE"$TITLETEXT" $MSGBOX $TEXT$"You have selected Backup Mode.\n\nDo not interrupt this process.\n\nClick OK to start the Backup Live CD/DVD process."
    xterm -fn 9x15 -e "sudo remastersys backup"

    SquashfsSizeCheckup

    FilesReady
}

distmenu() {
    $DIALOG $TITLE"$TITLETEXT" $MSGBOX $TEXT$"You have selected Dist Mode.\n\nClick OK to start the Distributable Live CD/DVD process."
    xterm -fn 9x15 -e "sudo remastersys dist"

    SquashfsSizeCheckup

    FilesReady
}

distcdfsmenu() {
    $DIALOG $TITLE"$TITLETEXT" $MSGBOX $TEXT$"You have selected Dist CDFS Mode.\n\nClick OK to start the Distributable Live CD/DVD file system build process."
    xterm -fn 9x15 -e "sudo remastersys dist cdfs"

    SquashfsSizeCheckup

    $DIALOG $TITLE"$TITLETEXT" $MSGBOX $TEXT$"Your Live CD File System is ready in $WORKDIR. You can now add files\nto the CD and then run the Dist ISO option when you are done.\n\nClick on OK to return to the main menu."

    mainmenu
}

distisomenu() {
    if [ -f "$WORKDIR/ISOTMP/live/filesystem.squashfs" ]; then
        $DIALOG $TITLE"$TITLETEXT" $MSGBOX $TEXT$"You have selected DistISO Mode.\n\nClick OK to create the ISO file."
        xterm -fn 9x15 -e "sudo remastersys dist iso"
        
        SquashfsSizeCheckup

        FilesReady
    else
        $DIALOG $TITLE"$TITLETEXT" $MSGBOX $TEXT$"The Live CD file system does not exist.\n\nClick OK to go back to the main menu and try the normal Dist mode or the Dist\nCDFS again."
        mainmenu
        exit 0
    fi
}

distbootmenu() {
    $DIALOG $TITLE"$TITLETEXT" $MSGBOX $TEXT$"This will allow you to choose your own picture to be the background for the LIVE\n\
boot menu. Please note that it MUST be a 640x480 pixel PNG file. You must create\n\
this picture or resize it with a proper graphics editor as this tool does not\n\
have the ability to change the size or type of picture.\n\n\
Click OK to continue."

    BOOTPIC=$($DIALOG $TITLE"$TITLETEXT" --width=750 --height=400 $FILESELECTION)
    
    # BOOTPIC extension
    BOOTPICext="${BOOTPIC: -4}"

    if [ "${BOOTPICext,,}" == ".png" ]; then # Extension lowercase

        sudo cp $BOOTPIC /etc/remastersys/isolinux/splash.png

        $DIALOG $TITLE"$TITLETEXT" --width=430 $MSGBOX $TEXT$"$BOOTPIC has been copied to /etc/remastersys/isolinux/splash.png becoming the\ndefault background for the LIVE menu.\n\nClick OK to continue."
    else
        $DIALOG $TITLE"$TITLETEXT" --width=430 $MSGBOX $TEXT"$NoFileSelected"
    fi

    mainmenu
}

distgrubmenu() {
    $DIALOG $TITLE"$TITLETEXT" $MSGBOX $TEXT$"This will allow you to choose your own PNG picture to be the background for the\nGRUB boot loader.\n\nClick OK to continue."

    GRUBPIC=$($DIALOG $TITLE"$TITLETEXT" --width=750 --height=400 $FILESELECTION)
    
    # GRUBPIC extension
    GRUBPICext="${GRUBPIC: -4}"

    if [ "${GRUBPICext,,}" == ".png" ]; then # Extension lowercase
        $DIALOG $TITLE"$TITLETEXT" $MSGBOX $TEXT$"$GRUBPIC has been copied to /etc/remastersys/grub.png and is the default\nbackground for grub.\n\nClick OK to update grub with the new settings so you can see your picture on the\nnext boot."

        if [ "$?" = "0" ]; then
            $DIALOG $TITLE"$TITLETEXT" --width=300 --no-buttons --progress --pulsate $TEXT$"Updating grub now.\n\nPlease wait." &
            PICFILE=$(echo $GRUBPIC | awk -F"/" '{print $NF}')
            sudo cp $GRUBPIC /etc/remastersys/grub.png
            NEWGRUBPIC="/etc/remastersys/grub.png"

            sudo sed -i -e "/#Grub Background/d" /etc/default/grub
            sudo sed -i -e "/GRUB_BACKGROUND/d" /etc/default/grub

            sudo cat >> /etc/default/grub <<FOO
#Grub Background
GRUB_BACKGROUND="$NEWGRUBPIC"
FOO

            sudo update-grub
            sudo killall -KILL yad

            $DIALOG $TITLE"$TITLETEXT" $MSGBOX $TEXT$"GRUB has been updated.\n\nClick OK to continue."
        fi
    else
        $DIALOG $TITLE"$TITLETEXT" $MSGBOX $TEXT"$NoFileSelected"
    fi

    mainmenu
}

distskelmenu() {
    $DIALOG $TITLE"$TITLETEXT" $MSGBOX $TEXT$"This will put your user desktop and application settings in /etc/skel so they\n\
become the default for the live system. This includes desktop background and\n\
other personalized application settings that aren't hardcoded to the current\n\
users home folder. Need to compile a list of valid users. It may take a few\n\
seconds to complete so be patient.\n\n\
Click OK to prepare the list."

    j="0"
    i="1000"
    
    while [ "$(cat /etc/passwd | awk -F ":" '{print $3}' | grep $i)" != "" ]; do
        for i in $(seq 1000 1 1010); do
            if [ "$(cat /etc/passwd | awk -F ":" '{print $3}' | grep $i)" != "" ]; then
                userchoice[$j]="$(grep $i /etc/passwd | awk -F ":" '{print $1}')"
                j=$(expr $j + 1)
            fi
        done
    done
    
    SelectUser=$"Please select a user whose settings \nyou would like to make the default. "

    SKELUSER=$($DIALOG $TITLE"$TITLETEXT" $MENU $TEXT"$SelectUser" \
    ${userchoice[0]} ${userchoice[0]} \
    ${userchoice[1]} ${userchoice[1]} \
    ${userchoice[2]} ${userchoice[2]} \
    ${userchoice[3]} ${userchoice[3]} \
    ${userchoice[4]} ${userchoice[4]} \
    ${userchoice[5]} ${userchoice[5]} \
    ${userchoice[6]} ${userchoice[6]} \
    ${userchoice[7]} ${userchoice[7]} \
    ${userchoice[8]} ${userchoice[8]} \
    ${userchoice[9]} ${userchoice[9]})

    SKELUSER=$(echo $SKELUSER | cut -d "|" -f 1)

    if [ "$SKELUSER" != "" ]; then
        cd $(grep "^$SKELUSER:" /etc/passwd | awk -F ":" '{print $6}')
        PWD=$(pwd)
        TESTUSER=$(grep "$PWD" /etc/passwd | awk -F ":" '{print $1}')

        if [ "$TESTUSER" != "$SKELUSER" ]; then
            $DIALOG $TITLE"$TITLETEXT" $MSGBOX $TEXT$"The user you chose does not have a proper home directory.\n\nClick OK to return to the main menu."
            echo $"Need to be in the user directory. Exiting."
            mainmenu
        fi

        $DIALOG $TITLE"$TITLETEXT" --no-buttons --progress --pulsate $TEXT$"Copying your $SKELUSER user settings to /etc/skel now.\n\nPlease wait." &

        sudo remastersys-skelcopy $SKELUSER

        sudo killall -KILL yad

        $DIALOG $TITLE"$TITLETEXT" $MSGBOX $TEXT$"The settings for $SKELUSER have been copied to /etc/skel. In order to test it\nout you need to create a new user and see if your settings have been applied.\n\nClick OK to return to the main menu."

    else
        $DIALOG $TITLE"$TITLETEXT" $MSGBOX $TEXT$"You didn't select any user.\n\nClick OK to continue."
    fi

    mainmenu
}

modifymenu() {
    if [ "$SQUASHFSOPTS" = "" ]; then
        SQUASHFSOPTS="-no-recovery -always-use-fragments -b 1M -comp zstd"
    fi
    
    LiveUsername=$"Live Username"
    LiveSystemName=$"Live System Name"
    LiveISOFilename=$"Live ISO Filename"
    LiveBoot=$"Live Boot using GRUB or ISOLINUX"
    WorkingDirectory=$"Working Directory for Remastersys"
    OptionsMksquashfs=$"Options for mksquashfs"
    ShowIcon=$"Show install icon on desktop"
    ExcludedFiles=$"Excluded files and folders"
    
    Save=$"Save"
    Back=$"Back"

    CHOICES=$($DIALOGMENU $TITLE"$TITLETEXT" --height=330 --button="$Save":0 --button="$Back":1 --form \
--field="$LiveUsername" "$LIVEUSER" \
--field="$LiveSystemName" "$LIVECDLABEL" \
--field="$LiveISOFilename" "$CUSTOMISO" \
--field="$LiveBoot" "$ISOBOOT" \
--field="$WorkingDirectory" "$WORKDIR" \
--field="$OptionsMksquashfs" " $SQUASHFSOPTS" \
--field="$ShowIcon" "$SHOWICON" \
--field="$ExcludedFiles" " $EXCLUDES")

    if [ "$?" = "0" ]; then
        LIVEUSER=$(echo $CHOICES | cut -d "|" -f 1)
        LIVECDLABEL=$(echo $CHOICES | cut -d "|" -f 2)
        CUSTOMISO=$(echo $CHOICES | cut -d "|" -f 3)
        ISOBOOT=$(echo $CHOICES | cut -d "|" -f 4)
        WORKDIR=$(echo $CHOICES | cut -d "|" -f 5)
        SQUASHFSOPTS=$(echo $CHOICES | cut -d "|" -f 6)
        SHOWICON=$(echo $CHOICES | cut -d "|" -f 7)
        EXCLUDES=$(echo $CHOICES | cut -d "|" -f 8)
    else
        mainmenu
    fi

    if [ "$LIVEUSER" = "" ]; then
        LIVEUSER="pearl"
    fi

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

    if [ "$LIVECDLABEL" = "" ]; then
        LIVECDLABEL="PearlMATE Studio 11"
    fi

    if [ "$CUSTOMISO" = "" ]; then
        CUSTOMISO="pearlmate-studio_11_2022.10.08_amd64.iso"
    fi

    if [ "$ISOBOOT" = "grub" -o "$ISOBOOT" = "GRUB" ]; then
        ISOBOOT="GRUB"
    else
        ISOBOOT="ISOLINUX"
    fi

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

    if [ "$SQUASHFSOPTS" = "" ]; then
        SQUASHFSOPTS="-no-recovery -always-use-fragments -b 1M -comp zstd"
    fi

    SHOWICON="$(echo $SHOWICON | awk '{print tolower ($0)}')"

    if [ "$SHOWICON" = "1" ]; then
        SHOWICON="1"
    elif [ "$SHOWICON" = "yes" ]; then
        SHOWICON="1"
    elif [ "$SHOWICON" = "true" ]; then
        SHOWICON="1"
    else
        SHOWICON="0"
    fi

    sudo cat > /etc/remastersys.conf <<FOO
# Remastersys Global Configuration File.

# This is the temporary working directory and won't be included on the CD/DVD.
BASEWORKDIR="$BASEWORKDIR"
WORKDIR="$WORKDIR"

# Here you can add any other files or directories to be excluded from the live
# file system. Separate each entry with a space.
EXCLUDES="$EXCLUDES"

# Here you can change the Live CD/DVD username.
LIVEUSER="$LIVEUSER"

# Here you can change the name of the Live CD/DVD label.
LIVECDLABEL="$LIVECDLABEL"

# Here you can change the name of the ISO file that is created.
CUSTOMISO="$CUSTOMISO"

# Here you can change the boot method for the live - GRUB or ISOLINUX.
ISOBOOT="$ISOBOOT"

# Options for mksquashfs.
# Default is: -no-recovery -always-use-fragments -b 1M -comp zstd
SQUASHFSOPTS="$SQUASHFSOPTS"

# Option to show install icon on live desktop in dist mode:
# 1=yes or true, 0=no or false.
SHOWICON="$SHOWICON"
FOO

    if [ "$?" = "0" ]; then
        $DIALOG $TITLE"$TITLETEXT" $MSGBOX $TEXT$"Configuration Saved.\n\nClick OK to return to the settings menu."
    else
        $DIALOG $TITLE"$TITLETEXT" $MSGBOX $TEXT$"Configuration Save Error.\n\nClick OK to return to the settings menu."
    fi

    modifymenu
}

cleanmenu() {
    $DIALOG $TITLE"$TITLETEXT" $MSGBOX $TEXT$"This will remove all the files from the temporary directory.\n\nClick OK to proceed."
    xterm -fn 9x15 -e "sudo remastersys clean"
    $DIALOG $TITLE"$TITLETEXT" $MSGBOX $TEXT$"Completed.\n\nClick OK to return to the main menu."
    mainmenu
}

mainmenu

