#!/usr/bin/perl

# vpsautomount v0.02
# by Dusty Wilson, dusty@conceptualarc.com
# Copyright 2006 Conceptual Arc, LLC
#
# Released under GPL license.  Leave the copyright notice intact.
# Read http://www.gnu.org/copyleft/gpl.html for your rights under the GPL.
#
# Disclaimer:  I, nor my employer, take responsibility for the use/misuse of this
# script or any damage that may result.  Use this at your own risk only.
#
# Change log:
# 2006-01-27: [Dusty Wilson] v0.01: Created initial version.
# 2006-01-28: [Dusty Wilson] v0.02: Added auto-unmount support if given VPS is stopped.
# 2006-01-28: [Dusty Wilson] Released as GPL.

my $VERSION = "0.02";

my $mount = `/sbin/mount`; # change this if the path is wrong
my $mounted = {};

foreach my $line (split(/\r?\n/, $mount)) {
  $line =~ m|^(.*?)\s+on\s+(.*?)\s+type|i;
  my $source = $1;
  my $target = $2;

  # $target =~ s|^/var/vz|/vz|; # I use this line because on our servers, /vz is a
                                # symlink to /var/vz and the OpenVZ config expects
                                # /vz not /var/vz (commented out by default,
                                # uncomment if you want to use it it .. most people
                                # will want to leave this line commented out)

  $mounted->{$target} = $source;
}

my $vzlist = `/usr/sbin/vzlist -Ha`; # change this if the path is wrong
my $running = {};

foreach my $line (split(/\r?\n/, $vzlist)) {
  $line =~ m|^\s*(\d+)\s+[\d-]+\s+(\S+)|;
  my $veid = $1;
  my $status = $2;
  $running->{$veid}= $status;
}

my @conffiles = glob("/etc/sysconfig/vz-scripts/*.conf"); # change this if the path is wrong

foreach my $file (@conffiles) {
  $file =~ m|/(\d+)\.conf$|i;
  my $veid = $1;
  #next unless ($running->{$veid} eq "running");
  my $mounts = {};
  my $root = "/dev/null";
  if (open(CF, "<$file")) {
    while (my $line = <CF>) {
      if ($line =~ m|^VE_ROOT=(['"])(.*?)\1|i) {
        $root = $2;
        $root =~ s|\$VEID|$veid|gi;
      }
      if ($line =~ m|^CA_MOUNT_(\d+)_(.*?)=(['"])(.*?)\3|i) {
        my $id = $1;
        my $type = lc($2);
        my $value = $4;
        if ($type eq "dest") {
          $value = "$root$value";
        }
        $mounts->{$id}->{$type} = $value;
      }
    }
    close(CF);
    foreach my $id (keys(%{$mounts})) {
      next unless ($mounts->{$id}->{src} && $mounts->{$id}->{dest});
      my $src = $mounts->{$id}->{src};
      my $dest = $mounts->{$id}->{dest};
      if ($running->{$veid} eq "running") {
        next if ($mounted->{$dest});
        unless (-e $dest) {
          mkdir($dest);
        }
        my $domount = `/sbin/mount --bind "$src" "$dest" && echo 1`; # change this if the path is wrong
      }
      else {
        next unless ($mounted->{$dest});
        my $dounmount = `/sbin/umount "$dest" && echo 1`; # change this if the path is wrong
      }
    }
  }
}