/*
 * Guillaume Cottenceau (gc)
 *
 * Copyright 2000 Mandriva
 *
 * This software may be freely redistributed under the terms of the GNU
 * public license.
 *
 * 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., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 */

/*
 * Portions from Erik Troan (ewt@redhat.com)
 *
 * Copyright 1996 Red Hat Software 
 *
 */

// for asprintf:
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/mount.h>
#include <sys/stat.h>
#include <sys/types.h>
#include "log.h"
#include "utils.h"
#include "modules.h"

#include "mount.h"



/* WARNING: this won't work if the argument is not /dev/ based */
int ensure_dev_exists(const char * dev)
{
	struct stat buf;
	
	if (!stat(dev, &buf))
		return 0; /* if the file already exists, we assume it's correct */

	// give udev some time to create nodes if module was just insmoded:
	system("udevadm settle");

	if (!stat(dev, &buf)) {
		log_message("I don't know how to create device %s, please post bugreport to me!", dev);
		return -1;
	}
	
	return 0;
}


/* mounts, creating the device if needed+possible */
int my_mount(char *dev, char *location, char *fs, int force_rw)
{
	char * opts = NULL;
	struct stat buf;
	int rc;

	if (strcmp(fs, "nfs")) {
	    rc = ensure_dev_exists(dev);
	    if (rc != 0) {
		    log_message("could not create required device file");
		    return -1;
	    }
	}

	log_message("mounting %s on %s as type %s", dev, location, fs);

	if (stat(location, &buf)) {
		if (mkdir(location, 0755)) {
			log_perror("could not create location dir");
			return -1;
		}
	} else if (!S_ISDIR(buf.st_mode)) {
		log_message("not a dir %s, will unlink and mkdir", location);
		if (unlink(location)) {
			log_perror("could not unlink");
			return -1;
		}
		if (mkdir(location, 0755)) {
			log_perror("could not create location dir");
			return -1;
		}
	}

#ifndef DISABLE_MEDIAS
	if (!strcmp(fs, "nfs"))
		opts = "nolock";
	if (!strcmp(fs, "vfat"))
		opts = "check=relaxed";
#endif
	char *cmd;
	rc = asprintf(&cmd, "mount %s %s -t %s -o %s%s > /dev/null 2>&1", dev, location, fs, (force_rw ? "" : "ro,"), (opts ? opts : ""));
	if (rc == -1) {
		log_perror("asprint allocation failure");
		rmdir(location);
		return rc;
	}
	rc = system(cmd);
	if (rc != 0) {
		log_perror("mount failed");
		rmdir(location);
	}

	return rc;
}
