#!/usr/bin/env python3

# Set BIRCH_PLATFORM environment variable in platform.source
# and platform.profile.source by uncommenting one of the
# lines in each file.

#Synopsis: setplatform.sh platform
#

import os, os.path, stat, sys, shutil

def chmod_ar(filename):
    if os.path.exists(filename):
            st = os.stat(filename)
            os.chmod(filename, st.st_mode | stat.S_IREAD \
                | stat.S_IRGRP | stat.S_IROTH)

def replaceAll(file, searchExp, replaceExp):
    shutil.move( file, file + "~" )
    destination = open( file, "w" )
    source= open( file + "~", "r" )
    for line in source:
        if searchExp in line:
            line = line.replace(searchExp,replaceExp)
        destination.write( line )
    source.close()
    destination.close()

def setplatform(BASEDIR = os.path.abspath(os.path.join(os.getcwd(), os.pardir))):
    PLAT_SRC = os.path.join(BASEDIR, "local", "admin", "platform.source")
    PROF_SRC = os.path.join(BASEDIR, "local", "admin", "platform.profile.source")

    if len(sys.argv) < 1:
        print ("setplatform.sh: ERROR! YOU NEED TO SPECIFY A PLAFORM!")
    platform = sys.argv[1]

    if platform in ["solaris-sparc", "solaris-amd64", "linux-arm64", "linux-x86_64", "osx-x86_64", "macos-arm64", "win7-64" ]:

        replaceAll(PLAT_SRC, "#setenv BIRCH_PLATFORM " + platform, "setenv BIRCH_PLATFORM " + platform)
        chmod_ar(PLAT_SRC)
        replaceAll(PROF_SRC, "#BIRCH_PLATFORM=" + platform, "BIRCH_PLATFORM=" + platform)
        chmod_ar(PROF_SRC)
    else:
        print ('setplatform.sh: invalid platform (' + platform + ')')
        sys.exit(1)

if __name__=="__main__":
    setplatform(sys.argv[1])
