#!/usr/bin/python

"""
regen_indexphp_webdirs.py

  - regenerates the index.php files on the web server for all web server
    directory paths listed in a text listing of web paths
  - using comments below as toggles, can also reset permissions on files
    in web and ftp directories to chmod 644, i.e. -rw-r--r--

based on:  copy_web_hdf_to_nc4.py

input:     reads a text listing of web paths
           ( the file containing the text listing is hardcoded below )

usage:     ./regen_indexphp_webdirs.py

Ron Vogel, SMRC for NOAA CoastWatch
Apr 18, 2017
"""

import sys
#import re
import os
#import shutil
import commands


#web_home = '/data/www-socd/mecb/ecn/data'
#web_dir_listings = [ 'web_directories_MODIS.txt',
#                     'web_directories_MODIS_2.txt',
#                     'web_directories_SST.txt',
#                     'web_directories_PODAAC.txt',
#                     'web_directories_TEST.txt',
#                     'web_directories_VIIRS.txt' ]

# for resetting file permissions on ECN ftp site:
web_home = '/data/aftp/socd1/ecn/data'
web_dir_listings = [ 'ftp_directories_MODIS.txt',
                     'ftp_directories_MODIS_2.txt',
                     'ftp_directories_AVHRR.txt',
                     'ftp_directories_GOES_GEOPOL.txt',
                     'ftp_directories_PODAAC_ALL.txt',
                     'ftp_directories_PODAAC_TEST.txt',
                     'ftp_directories_VIIRS.txt' ]


for web_dir_listing in web_dir_listings:

  web_dir_list = open(web_dir_listing, 'r')

  # Example line entry in listings:  "mkdir $HOME/modis/k490noaa/daily/ob"
  # ( listing file is based on make_directories_web.sh )

  for web_line in web_dir_list:
     web_line_stripd = web_line.strip()      # remove whitespace

     # determine path to data on web server
     dir_indx = web_line_stripd.find('/')
     web_dir = web_line_stripd[dir_indx:]
     web_path = web_home + web_dir

     print "Web path: ", web_path

     # test directory exists
     web_path_exists = os.path.exists(web_path)
     if web_path_exists:
         try:
            #cmd = 'cd ' + web_path + ' ; /disks/data033/scripts/utilities/update_indicatrix.pl -r'
            cmd = 'chmod 644 ' + web_path + '/*'
            (status, output) = commands.getstatusoutput(cmd) # if error, command
                                                    # fails & status is non-zero
            if status:    # status is true (non-zero) upon cmd failure 
               sys.stderr.write(output)  # writes error message
               print '\n'
         except:
            #print "Error cd'ing to web directory OR running update_indicatrix.pl:"
            print "Error resetting file permissions to chmod 644:"
            print "   ", web_path
            print sys.exc_info()[0]
     else:
         print "Problem: the web directory path does not exist"
         print "         ", web_path

  web_dir_list.close()

