#! /usr/bin/env bash
# Copyright (C) 2010 Sebastian Pipping <sebastian@pipping.org>
# Licensed under GPL v2 or later
# 2010-12-03 08:57 UTC+1
#
# Purpose:
#   Makes a wrapfs snapshot tarball to allow distribution as a standlone kernel module
#
# Usage:
#   git clone git://git.fsl.cs.sunysb.edu/wrapfs-latest.git
#   cd wrapfs-latest
#   cp SOMEWHERE/wrapfs-snapshot.sh .
#   ./wrapfs-snapshot.sh

die() {
	echo $@
	exit 1
}

VERSION=$(/bin/grep '^WRAPFS_VERSION=' fs/wrapfs/Makefile | sed 's/WRAPFS_VERSION="\(.\+\)"/\1/')
[ $(wc -l <<<"${VERSION}") == 1 ] || die 'grepping WRAPFS_VERSION failed'
VERSION="${VERSION}_p$(date +'%Y%m%d')"
DISTNAME="wrapfs-${VERSION}"


# Reset
if [[ -n "${DISTNAME}" && -d "${DISTNAME}" ]]; then
	echo 'Cleaning up...'
	rm -Rfv "${DISTNAME}"
	echo
fi
mkdir -p "${DISTNAME}" || die 'mkdir failed'


# Code
cp fs/wrapfs/*.{c,h} "${DISTNAME}"/ || die 'cp failed'

# Patch: Integrate WRAPFS_SUPER_MAGIC
wrapfs_super_magic_line=$(fgrep WRAPFS_SUPER_MAGIC include/linux/magic.h)
[ $(wc -l <<<"${wrapfs_super_magic_line}") == 1 ] || die 'grepping WRAPFS_SUPER_MAGIC failed'
sed 's|^#include "wrapfs.h"|&\n'"${wrapfs_super_magic_line}"'|' -i "${DISTNAME}"/super.c

# Patch: Turn into module, update version
sed \
	-e 's|^WRAPFS_VERSION=.*|WRAPFS_VERSION="'"${VERSION}"'"|' \
	-e 's|$(CONFIG_WRAP_FS)|m|' \
	fs/wrapfs/Makefile \
	> "${DISTNAME}"/Makefile

# Readme
cp Documentation/filesystems/wrapfs.txt "${DISTNAME}"/README || die 'cp failed'

# Author and contact info
fgrep -A6 WRAPFS MAINTAINERS > "${DISTNAME}"/AUTHORS

# Install instructions
cat <<-EOF >"${DISTNAME}"/INSTALL
	tar -xvjf ${DISTNAME}.tar.gz
	cd ${DISTNAME}
	make -C /lib/modules/\`uname -r\`/build M=\`pwd\` modules
	make -C /lib/modules/\`uname -r\`/build M=\`pwd\` modules_install
	modprobe wrapfs
EOF


# Archive
echo 'Archiving...'
tar -cjvf "${DISTNAME}".tar.bz2 "${DISTNAME}"
echo

target_kernel=$(git describe | sed 's|^v\(.\+\)-[0-9]\+-g.*|\1|')
echo "Done.  Target kernel is ${target_kernel}."
