#!/usr/bin/env zsh
# Copyright (c) 2017 Dyne.org Foundation
# libdevuansdk is maintained by Ivan J. <parazyd@dyne.org>
#
# This file is part of libdevuansdk
#
# This source code is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This software is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this source code. If not, see <http://www.gnu.org/licenses/>.

aptcache() {
    fn aptcache "$*"
    req=(aptcachedir watdo werdo APT_CACHE)
    local watdo="$1"
    local werdo="$2"
    ckreq || return 1

    [[ $APT_CACHE = 1 ]] || return 0

    case "$watdo" in
        on)
            act "mounting local apt cache"
            sudo mount -o bind "$aptcachedir" "$werdo" || zerr
            ;;
        off)
            act "umounting local apt cache"
            sudo umount "$werdo" || zerr
            ;;
    esac
}

fill_apt_cache() {
    fn fill_apt_cache
    req=(strapdir APT_CACHE aptcachedir)
    ckreq || return 1

    [[ $APT_CACHE = 1 ]] || return 0

    notice "filling local apt cache"

	cp -fv $strapdir/var/cache/apt/archives/*.deb $aptcachedir

	pushd "$aptcachedir"
		dpkg-scanpackages . /dev/null > Packages
		gzip -c Packages > Packages.gz
		cat <<EOF > Release
Origin: ${os}
Suite: ${release}
Version: ${version}
Architectures: alpha amd64 arm64 armel armhf hppa i386 ia64 mips mipsel powerpc ppc64el s390x sparc
MD5sum:
 $(md5sum Packages    | cut -d' ' -f1)    $(du -b Packages)
 $(md5sum Packages.gz | cut -d' ' -f1)    $(du -b Packages.gz)
SHA1:
 $(sha1sum Packages    | cut -d' ' -f1)    $(du -b Packages)
 $(sha1sum Packages.gz | cut -d' ' -f1)    $(du -b Packages.gz)
SHA256:
 $(sha256sum Packages    | cut -d' ' -f1)    $(du -b Packages)
 $(sha256sum Packages.gz | cut -d' ' -f1)    $(du -b Packages.gz)
EOF
		rm -f Packages
		gpg --sign --detach-sign -a --sign-with $aptcachegpg Release || zerr
		mv Release.asc Release.gpg
	popd


	sudo sed -i '/deb file:\/mnt/d' "$strapdir/etc/apt/sources.list"
	notice "removing apt cache gpg pubkey"
	cat <<EOF | sudo tee ${strapdir}/delcachepubkey >/dev/null
#!/bin/sh
apt-key del ${aptcachegpg}
EOF
	chroot-script delcachepubkey || zerr
}
