#!/usr/bin/perl -w
#
# Generate systemd mount units based on information from fstab file.
#
# Copyright (C) 2012 Samsung Electronics
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# version 2 as published by the Free Software Foundation.
#
# This program 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 program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
#
# Author: Łukasz Stelmach <l.stelmach@samsung.com>
#
use strict;
use Cwd 'abs_path';

my $out_dir = pop @ARGV;
my ($fs_dev, $fs_dir, $fs_type, $fs_opts, $fs_dump, $fs_pass);

sub name_from_path($) {
	my $dev=shift;
	$dev =~ s:/+:-:g;

	if ($dev=~m/^-$/) {
		return $dev;
	}

	$dev =~ s/^-|-$//g;
	return $dev;
}

while(<>) {
	chomp;
	($fs_dev, $fs_dir, $fs_type, $fs_opts, $fs_dump, $fs_pass)=split;
	next unless ($fs_dev=~m/mmcblk/);
	next unless ($fs_type=~m/ext[234]/);

	my $fs_tab=abs_path $ARGV;
	my $unit_name=$out_dir ."/". name_from_path($fs_dir) . ".mount";
	my $devname=name_from_path $fs_dev;
	my ($after,$req,$wants);
	if ($fs_dir eq "/") {
	    $after = "fsck-root.service resize2fs-root.service";
	    $req = "fsck-root.service";
	    $wants = "resize2fs-root.service";
	} else {
	    $after = "fsck\@$devname.service resize2fs\@$devname.service";
	    $req = "fsck\@$devname.service";
	    $wants = "resize2fs\@$devname.service";
	}

	my $unit=<<EOF;
# Automaticall generated by mount-generator.pl

[Unit]
# FIXME: Is this required?
#SourcePath=$fs_tab
DefaultDependencies=no
Before=local-fs.target
Requires=$req
After=local-fs-pre.target $after
Wants=$wants

[Mount]
What=$fs_dev
Where=$fs_dir
Type=$fs_type
Options=$fs_opts
EOF
	open (UNIT, ">", $unit_name) || die $!;
	print UNIT $unit,"\n";
	close UNIT;
}
