#!/bin/bash

# Maintainer: EndeavourOS-Team <info@endeavouros.com>

pkgname=EndeavourOS-ISO
pkgver=0.11
pkgrel=5
pkgdesc="Build EndeavourOS ISO"
arch=(any)
makedepends=(archiso mkinitcpio-archiso git squashfs-tools)
source=(git+https://github.com/endeavouros-team/$pkgname.git)
sha512sums=('SKIP')

_create_cleanup_script() {
    # There may be lots of files to delete:
    local installer_files=(
        cleaner_script.sh chrooted_cleaner_script.sh calamares_switcher update-mirrorlist
        pacstrap_calamares calamares_for_testers rank_pacman_key.sh
    )
    local file=run_before_squashfs.sh
    if [ -r $file ] ; then
        installer_files=($(grep "^mv " $file | grep "/usr/bin/$" | sed -e 's|^mv ||' -e 's| /usr/bin/$||'))
    fi
    installer_files+=(update-mirrorlist)

    cat <<EOF > "$cleanup"
#!/bin/bash
rm -f  ${pkgname}-*.pkg.tar.*
rm -rf ${pkgname}
rm -rf pkg
rm -rf src

# pushd /usr/bin
# sudo rm -fv "${installer_files[@]}"
# popd
           
sync
rm -f \$(basename $cleanup)         # underlying folder no more exists...
EOF
    chmod +x "$cleanup"
}

build() {
    ###################################################
    # Create a cleanup script.
    ###################################################

    local build_rootdir="$srcdir/.."
    local cleanup="$build_rootdir/cleanup.bash"
    local basedir=$srcdir/$pkgname
    local date iso

    _create_cleanup_script

    ###################################################
    # Build.
    ###################################################

    cd $srcdir/$pkgname
    pwd

    sudo pacman -Syyu || return 1

    # get extra drivers!
    #sudo pacman -Sw --noconfirm --cachedir airootfs/opt/extra-drivers r8168
    #sudo chown -R liveuser:users airootfs/opt

    local tmpdir
    local tmpsize=$(LANG=C /usr/bin/df | grep -w /tmp | awk '{print $4}')

    if [ $tmpsize -lt $((10*1000*1000)) ] ; then
	tmpdir=$(mktemp -d $HOME/.cache/foobar.XXXXX)
    else
	tmpdir=$(mktemp -d)
    fi

    cp -R "$PWD" $tmpdir/ || return 1

    date=$(date +%Y.%m.%d)
    iso=endeavouros-${date}-x86_64.iso
    
    pushd $tmpdir/$pkgname >/dev/null
    if [ "$FAKE_BUILD_TEST" != "yes" ] ; then
        sudo ./fix_permissions.sh
        time sudo ./mkarchiso -o $build_rootdir . | tee $build_rootdir/eos-iso-build.log
    else
        touch $build_rootdir/$iso
    fi
    popd >/dev/null
    sudo rm -rf $tmpdir
    cd ../..

    [ -n "$iso" ] || {
        # maybe the iso has the next date?
        date=$(date +%Y.%m.%d)
        iso=endeavouros-${date}-x86_64.iso
    }
    [ -n "$iso" ] || {
        # iso may have a different naming structure
        iso="$(/usr/bin/ls -1 endeavouros-*-x86_64.iso | tail -n1)"
    }
    [ -n "$iso" ] || {
        echo "ISO build failed." >&2
        return 1
    }

    sudo chown $LOGNAME $iso

    if [ -L testing.iso ] ; then
        # create a symlink if it already exists
        rm -f testing.iso
        ln -s $iso testing.iso
    fi

    sync

    ###################################################
    # Show the result.
    ###################################################

    cd "$build_rootdir"

    echo ""
    echo "#######################################################################"
    echo ""
    echo "The new ISO is here:"
    ls -1 "$build_rootdir"/$iso
    echo ""
    echo "To clean up all except the ISO, run command:"
    echo "    bash $cleanup"
    echo ""
    echo "#######################################################################"
    echo ""
}

package() {

    cd $srcdir/..

    local isofile=$(ls -1 endeavouros-*-x86_64.iso | grep -v devel | tail -n1)   # $isofile = endeavouros-<date>-x86_64.iso
    [ -n "$isofile" ] || {
        echo "no isofile"
        return 1
    }
    local isobase=$(basename $isofile .iso)                                      # $isobase = endeavouros-<date>-x86_64
    local date=$(echo $isofile | sed 's|endeavouros-\([0-9][0-9.]*\)-.*|\1|')    # date from the ISO file name

    printf "Create the sha512sum file ... "
    sha512sum $isofile 2>/dev/null > $isofile.sha512sum || true
    [ -r $isofile.sha512sum ] && echo "done" || echo "FAILED"

    printf  "Create the signature file ... "
    gpg --default-key info@endeavouros.com \
        --detach-sign \
        --output $isofile.sig \
        $isofile >& /dev/null || true
    [ -r $isofile.sig ] && echo "done" || echo "FAILED"

    printf "Create the torrent file ... "
    mktorrent -p -v \
              --announce=udp://tracker.openbittorrent.com:80 \
              -a udp://tracker.torrent.eu.org:451/announce \
              -a udp://thetracker.org:80/announce \
              -a udp://tracker.dutchtracking.com:6969/announce \
              -a udp://tracker.opentrackr.org:1337/announce \
              -c $isofile \
              -n $isofile \
              -o $isofile.torrent \
              -w https://mirror.alpix.eu/endeavouros/iso/$isofile \
              $isofile >& /dev/null || true
    [ -r $isofile.torrent ] && echo "done" || echo "FAILED"

    echo Done.
}
