#!/usr/bin/env python
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 textwidth=79 autoindent

"""
Python source code
Last modified: 12 Dec 2013 - 14:43
Last author: Laban Mwangi

Calculates the start of a process based on it's /proc/pid/stat file and 
the system uptime from /proc/uptime.
Rough hewn -  No exception handling

Example:
# echo python pid_start.py -p $$
python pid_start.py -p 8153

# python pid_start.py -p $$
Process  8153 started 1:05:28.800000 ago
Start time:  2013-12-12 13:56:39.081335

"""
import optparse
import os
import sys
import datetime

def calc_pid_start_time (args):
    pid =  args.pid
    clock_ticks = os.sysconf("SC_CLK_TCK")
    start_time_after_boot = float(open("/proc/%d/stat" % pid).read().split()[21])
    seconds_since_boot = float(open("/proc/uptime").read().split()[0])
    start_time_seconds =  seconds_since_boot - start_time_after_boot / clock_ticks
    start_time_delta = datetime.timedelta(seconds=start_time_seconds)
    print "Process  %d started %s ago" % (pid, start_time_delta)
    print "Start time: ", datetime.datetime.now() - start_time_delta

def main():
    """Main function. Called when this file is a shell script"""
    usage = "usage: %prog [options]"
    parser = optparse.OptionParser(usage)

    parser.add_option("-p", "--pid", dest="pid",
                      default="1", type="int",
                      help="PID of process")

    (options, args) = parser.parse_args()
    calc_pid_start_time(options)

if __name__ == '__main__':
    main()