#!/usr/bin/env ruby
# encoding: UTF-8

require 'json'
require_relative '.utils'

exit(0) if !File.exist?(LSU_TMPDIR_PATH)

user    = `id -un`.chomp
mounted = JSON.parse(`mount --libxo json`)['mount']['mounted']
tmpdir  = File.realpath(LSU_TMPDIR_PATH)

paths = mounted
  .find_all{|m| m['mounter'] == user && m['node'].start_with?(tmpdir)}
  .map     {|m| m['node']}
  .sort
  .reverse

for path in paths
  cmd = ['umount', path]
  pwarn format_cmd(cmd)
  if !system(*cmd)
    cmd = ['umount', '-f', path]
    pwarn format_cmd(cmd)
    if !system(*cmd)
      pwarn "Failed to unmount #{path}"
    end
  end
end
