#!/bin/bash
#
#-
#Copyright (c) 2009-2015 Juan Romero Pardines.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions and the following disclaimer in the
#    documentation and/or other materials provided with the distribution.
#
# Adapted by the Peppermint Team. Copyright (c) 2024 The Peppermint Team.
# All rights reserved.
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR
# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
# IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
# NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
# THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#-

set -eu

. ./lib.sh

PROGNAME=$(basename "$0")
ARCH=$(uname -m)
IMAGES="xfce"
TRIPLET=
REPO=
DATE=$(date -u +%Y%m%d)
ARCH="${ARCH:-$(uname -m)}"
LOG_DIR="$(dirname "$0")/log"
LOGFILE="${LOG_DIR}/build-iso-${DATE}-${ARCH}-${IMAGES}.log"
exec > >(tee -a "$LOGFILE") 2>&1

usage() {
	cat <<-EOH
	Usage: $PROGNAME [options ...] [-- mklive options ...]

	Wrapper script around mklive.sh for several standard flavors of live images.
	Adds pep-installer and other helpful utilities to the generated images.

	OPTIONS
	 -a <arch>     Set XBPS_ARCH in the image
	 -b <variant>  One of base, enlightenment, xfce, mate, cinnamon, gnome, kde,
	               lxde, or lxqt (default: base). May be specified multiple times
	               to build multiple variants
	 -d <date>     Override the datestamp on the generated image (YYYYMMDD format)
	 -t <arch-date-variant>
	               Equivalent to setting -a, -b, and -d
	 -r <repo>     Use this XBPS repository. May be specified multiple times
	 -h            Show this help and exit
	 -V            Show version and exit

	Other options can be passed directly to mklive.sh by specifying them after the --.
	See mklive.sh -h for more details.
	EOH
}

while getopts "a:b:d:t:hr:V" opt; do
case $opt in
    a) ARCH="$OPTARG";;
    b) IMAGES="$OPTARG";;
    d) DATE="$OPTARG";;
    r) REPO="-r $OPTARG $REPO";;
    t) TRIPLET="$OPTARG";;
    V) version; exit 0;;
    h) usage; exit 0;;
    *) usage >&2; exit 1;;
esac
done
shift $((OPTIND - 1))

INCLUDEDIR=$(mktemp -d)
trap "cleanup" INT TERM

cleanup() {
    rm -rf "$INCLUDEDIR"
}

setup_pipewire() {
    PKGS="$PKGS pipewire alsa-pipewire"
    mkdir -p "$INCLUDEDIR"/etc/xdg/autostart
    ln -sf /usr/share/applications/pipewire.desktop "$INCLUDEDIR"/etc/xdg/autostart/
    mkdir -p "$INCLUDEDIR"/etc/pipewire/pipewire.conf.d
    ln -sf /usr/share/examples/wireplumber/10-wireplumber.conf "$INCLUDEDIR"/etc/pipewire/pipewire.conf.d/
    ln -sf /usr/share/examples/pipewire/20-pipewire-pulse.conf "$INCLUDEDIR"/etc/pipewire/pipewire.conf.d/
    mkdir -p "$INCLUDEDIR"/etc/alsa/conf.d
    ln -sf /usr/share/alsa/alsa.conf.d/50-pipewire.conf "$INCLUDEDIR"/etc/alsa/conf.d
    ln -sf /usr/share/alsa/alsa.conf.d/99-pipewire-default.conf "$INCLUDEDIR"/etc/alsa/conf.d
}

build_variant() {
    variant="$1"
    shift
    IMG=pep-live-${ARCH}-${DATE}-${variant}.iso

    echo "Building variant: $variant, Image: $IMG"

    GRUB_PKGS="grub-i386-efi \
                                 grub-x86_64-efi \
                                 efitools \
                                 sbsigntool \
                                 tpm-tools \
                                 tpm2-tools"

    A11Y_PKGS="espeakup \
                               void-live-audio brltty"

    XORG_PKGS="xorg xorg-input-drivers \
                                  xorg-video-drivers \
                                  xf86-video-intel \
                                  setxkbmap \
                                  xauth \
                                  font-misc-misc \
                                  terminus-font \
                                  dejavu-fonts-ttf \
                                  orca"

   FIRMWARE_PKGS="linux-firmware \
                                           broadcom-bt-firmware \
                                           alsa-firmware \
                                           linux-firmware-qualcomm \
                                           qemu-firmware \
                                           sof-firmware"

    SHARED_PKGS="dialog \
                                      octoxbps \
                                      plymouth \
                                      cryptsetup \
                                      lvm2 \
                                      mdadm \
                                      rsync \
                                      void-docs-browse \
                                      xtools \
                                      xmirror \
                                      chrony \
                                      void-repo-nonfree \
                                      gvfs-afc \
                                      gvfs-mtp \
                                      gvfs-smb \
                                      udisks2 \
                                      alsa-utils \
                                      bluez \
                                      bluez-cups \
                                      btop \
                                      console-setup \
                                      cups \
                                      curl \
                                      dconf-editor \
                                      dbus-x11 \
                                      cantarell-fonts \
                                      liberation-fonts-ttf \
                                      git \
                                      wget \
                                      gparted \
                                      gvfs \
                                      samba \
                                      samba-cups \
                                      cups-pdf \
                                      avahi \
                                      inxi \
                                      ntp \
                                      python3-pipx \
                                      smartmontools \
                                      smbclient \
                                      spice-vdagent \
                                      sqlite \
                                      openssh \
                                      nano \
                                      vim-x11 \
                                      vim  \
                                      python3-tkinter \
                                      python3-requests \
                                      python3-certifi \
                                      python3-Pillow \
                                      blueman \
                                      zip \
                                      p7zip \
                                      blueman \
                                      gnome-keyring \
                                      NetworkManager \
                                      network-manager-applet \
                                      luakit \
                                      peppermint-repo \
                                      $A11Y_PKGS \
                                      $GRUB_PKGS \
                                      $XORG_PKGS \
                                      $FIRMWARE_PKGS"

    SHARED_SERVICES="sshd \
                                              chronyd \
                                              dbus \
                                              polkitd \
                                              bluetoothd \
                                              cupsd \
                                              avahi-daemon \
                                              ntpd \
                                              smbd \
                                              nmbd \
                                              sshd \
                                              spice-vdagentd \
                                              NetworkManager"

   LIGHTDM_PKGS="lightdm \
                          lightdm-gtk3-greeter \
                          lightdm-gtk-greeter-settings"

    INSTALLER_PKGS="calamares"

    XFCE_PKGS="xfce4 \
                                 xfce4-pulseaudio-plugin \
                                 xfce4-panel-profiles \
                                 xfce4-plugins \
                                 xfce4-screenshooter \
                                 mousepad \
                                 mugshot \
                                 menulibre \
                                 thunar-archive-plugin \
                                 thunar-volman \
                                 xfce4-plugins \
                                 xfce4-screenshooter \
                                 xarchiver \
                                 gnome-disk-utility \
                                 system-config-printer \
                                 simple-scan \
                                 gnome-themes-standard"

    XFCE_LOADED_PKGS="xfce4 \
                                                   xfce4-pulseaudio-plugin \
                                                   xfce4-panel-profiles \
                                                   xfce4-plugins \
                                                   xfce4-screenshooter \
                                                   mousepad \
                                                   mugshot \
                                                   menulibre \
                                                   thunar-archive-plugin \
                                                   thunar-volman \
                                                  xfce4-plugins \
                                                  xfce4-screenshooter \
                                                  xarchiver \
                                                 gnome-disk-utility \
                                                 system-config-printer \
                                                 simple-scan \
                                                 gnome-themes-standard"

    MATE_PKGS="mate \
                                 mate-extra"

    KDE_PKGS="kde5 \
                               konsole \
                               dolphin"

    LXQT_PKGS=" lxqt \
                                  sddm"

    case $variant in
        xfce)
            PKGS="$XORG_PKGS \
            $SHARED_PKGS \
            $INSTALLER_PKGS \
            $LIGHTDM_PKGS \
            $XFCE_PKGS "
            SERVICES="$SHARED_SERVICES \
                                  lightdm"
            LIGHTDM_SESSION=xfce
        ;;
        mate)
            PKGS="$XORG_PKGS \
            $SHARED_PKGS \
            $INSTALLER_PKGS \
            $LIGHTDM_PKGS \
            $MATE_PKGS "
            SERVICES="$SHARED_SERVICES \
                                  lightdm"
            LIGHTDM_SESSION=mate
        ;;
        kde)
            PKGS="$XORG_PKGS \
            $SHARED_PKGS \
            $INSTALLER_PKGS \
            $KDE_PKGS"
            SERVICES="$SHARED_SERVICES \
                                  sddm"
        ;;
        lxqt)
            PKGS="$XORG_PKGS \
            $SHARED_PKGS \
            $INSTALLER_PKGS \
            $LXQT_PKGS"
            SERVICES="$SHARED_SERVICES \
                                  sddm \
                                  wpa_supplicant"
        ;;
        xfce-loaded)
                           PKGS="$XORG_PKGS \
                           $SHARED_PKGS \
                          $INSTALLER_PKGS \
                          $LIGHTDM_PKGS \
                          $XFCE_LOADED_PKGS "
                          SERVICES="$SHARED_SERVICES \
                                                lightdm"
                          LIGHTDM_SESSION=xfce
        ;;
        *)
            >&2 echo "Unknown variant $variant"
            exit 1
        ;;
    esac

    if [ -n "$LIGHTDM_SESSION" ]; then
        mkdir -p "$INCLUDEDIR"/etc/lightdm
        echo "$LIGHTDM_SESSION" > "$INCLUDEDIR"/etc/lightdm/.session
        # needed to show the keyboard layout menu on the login screen
        cat <<- EOF > "$INCLUDEDIR"/etc/lightdm/lightdm-gtk-greeter.conf
[greeter]
indicators = ~host;~spacer;~clock;~spacer;~layout;~session;~a11y;~power
EOF
    fi

    if [ "$variant" != base ]; then
        setup_pipewire
    fi

    ./mklive.sh -a "$ARCH" -o "$IMG" -p "$PKGS" -S "$SERVICES" -I "$INCLUDEDIR" ${REPO} "$@"

	cleanup
}

if [ ! -x mklive.sh ]; then
    echo mklive.sh not found >&2
    exit 1
fi

if [ -n "$TRIPLET" ]; then
    VARIANT="${TRIPLET##*-}"
    REST="${TRIPLET%-*}"
    DATE="${REST##*-}"
    ARCH="${REST%-*}"
    build_variant "$VARIANT" "$@"
else
    for image in $IMAGES; do
        build_variant "$image" "$@"
    done
fi

check_disk_space() {
    FREE_SPACE=$(df /var/www/html | awk 'NR==2 {print $4}')
    MIN_SPACE_REQUIRED=10000  # 10 GB in MB

    if [ "$FREE_SPACE" -lt "$MIN_SPACE_REQUIRED" ]; then
        echo "Not enough free space in /var/www/html. Required: $MIN_SPACE_REQUIRED MB, Available: $FREE_SPACE MB"
        exit 1
    fi
}

check_permissions() {
    if [ ! -w "/var/www/html" ]; then
        echo "You do not have write permissions to /var/www/html. Please check your permissions."
        exit 1
    fi
}

cleanup_old_files() {
    ISO_DIR="/var/www/html"  # Directory where ISOs are stored

    # Remove ISO and checksum files older than 2 days
    find "$ISO_DIR" -type f \( -name "*.iso" -o -name "*.iso.sha256" \) -mtime +2 -exec rm -f {} \;
    echo "Old ISOs and checksum files removed from $ISO_DIR"
}

generate_checksum_and_move_isos() {
SCRIPT_DIR="$(dirname "$(readlink -f "$0")")"  # Directory where the script (and ISO) is located
    TARGET_DIR="/var/www/html"  # Directory where ISOs and checksums will be moved

    # Generate checksums for each ISO file in the script directory
    for iso_file in "$SCRIPT_DIR"/*.iso; do
        if [ -f "$iso_file" ]; then
            checksum_file="${iso_file}.sha256"
            sha256sum "$iso_file" > "$checksum_file"
            echo "Checksum created for $iso_file"

            # Move both ISO and checksum to the target directory
            mv "$iso_file" "$TARGET_DIR"
            mv "$checksum_file" "$TARGET_DIR"
            echo "Moved $iso_file and $checksum_file to $TARGET_DIR"
        fi
    done
}

check_disk_space
check_permissions
cleanup_old_files
generate_checksum_and_move_isos

