#!/usr/bin/env python2.5

import sys
import os
from subprocess import call, Popen, PIPE

def losetup(source, offset=0):
  lockfilename = '/tmp/losetup.lock'
  os.close(os.open(lockfilename, os.O_CREAT+os.O_EXCL)) #lock
  try:
    loopdevice = Popen(['losetup', '-f'], stdout=PIPE).communicate()[0].rstrip()
    if loopdevice == '':
      raise RuntimeError('out of loop devices for copying VM image: too many at once?')
    if call(['losetup', '-o', str(offset), loopdevice, source]) != 0:
      raise RuntimeError('losetup failed')
  finally:
    os.unlink(lockfilename) #unlock
  return loopdevice

def main(*argv):
  args = argv[1:]
  os.environ['PATH'] = '/usr/sbin:/usr/bin:/sbin:/bin'
  if not (1 <= len(args) <= 2):
    print >>sys.stderr, 'usage: %s sourcedevice [offset]' % argv[0]
    print >>sys.stderr, 'prints resulting loopback device; don\'t forget to losetup -d'
    return 2
  print losetup(*args)
  return 0

if __name__ == '__main__':
  sys.exit(main(*sys.argv))
