#!/usr/bin/env python

# pt - pivot file over a command

# Copyright (c) 2015 Jason Schulz <https://github.com/uxcn>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

# author: jason

from __future__ import print_function

import sys

import os
import os.path

import shutil
import tempfile
import subprocess

c = sys.argv[0]

def on_error(e, x=1):
    if not e is None:
        print('%s: %s' % (c, e), file=sys.stderr)

    sys.exit(x)

if len(sys.argv) < 3:
    usage()

pd = None

if sys.argv[1] == '-p':

    pd = sys.argv[2]

    del sys.argv[1:3]

if len(sys.argv) > 1 and sys.argv[-2] == '-p':

    pd = sys.argv[-1]

    del sys.argv[-2:]

if len(sys.argv) < 3:
    usage()

pca = sys.argv[1:]

pf = sys.argv[-1]
pfa = os.path.abspath(pf)

if pd is None:
    pd = os.path.dirname(pfa)

if not os.path.exists(pfa):
    on_error('no such file or directory (%s)' % pf)

if not os.access(pfa, os.R_OK) or not os.access(pfa, os.W_OK):
    on_error('permission denied (%s)' % pf)

try:

    (ptf, pt) = tempfile.mkstemp(prefix='pt.', dir=pd)

except OSError as e:

    on_error(e.strerror)

try:

    shutil.copystat(pfa, pt)

except OSError as e:

    os.close(ptf)
    os.unlink(pt)

    on_error(e.strerror)

try:
    x = subprocess.call(pca, stdout=ptf)
except OSError as e:
    on_error('%s' % e.strerror)

if x is not 0:

    os.close(ptf)
    os.unlink(pt)

    on_error(None, x)

try:

    shutil.move(pt, pfa)

except OSError as e:

    os.close(ptf)
    os.unlink(pt)

    on_error('%s (%s -> %s)' % (e.strerror, pt, pfa))

# vim:ft=python:et:ts=4:sts=4:sw=4:tw=80
