#!/usr/bin/env python

#
# Installer for dedicated Models@Home cluster nodes without screen saver
#
# License: Public Domain

import string,os,shutil,fnmatch,crypt

# CREATE DIRECTORY LISTING INCLUDING FULL PATH NAMES
# ==================================================
def dsc_dirlist(path):
  # NORMALIZE PATH, IMPORTANT TO CONVERT UNIX FORWARD TO WINDOWS BACKWARD SLASHES
  path=os.path.normpath(os.path.normcase(path))
  # CREATE LIST OF ALL THE FILENAMES IN THE DIRECTORY SPECIFIED BY PATH
  (path,wildcard)=os.path.split(path)
  if (path==""): path="."
  try: filelist=os.listdir(path)
  except: return(None)
  # CYCLE THROUGH ALL FILES AND CHECK IF THEY MATCH WILDCARD
  i=0
  while (i<len(filelist)):
    if (fnmatch.fnmatch(filelist[i],wildcard)):
      filelist[i]=os.path.join(path,filelist[i])
      if (os.path.isfile(filelist[i])):
        i=i+1
        continue
    # NO MATCH
    del filelist[i]
  filelist.sort()
  return(filelist)

# MAIN SCRIPT
# ===========
print
print "Welcome to the Models@Home installer for dedicated cluster nodes"
print "================================================================"
print
print "More information available at www.yasara.com/models"
print "This installer has been tested with RedHat 8.0, but should work with"
print "most other Linux distributions."
print
password=raw_input("Input a new password for Models@Home user 'models' (or CTRL+C to stop):")

# CHECK IF libncurses.so.5 IS PRESENT
liblist=dsc_dirlist("/usr/lib/libncurses.so.*")
for lib in liblist:
  if (string.find(lib,"libncurses.so.5")!=-1): break
else:
  os.system("ln -s libncurses.so.5 "+liblist[0])

# CHECK IF SDL LIBRARY IS PRESENT (GET FROM www.libsdl.org)
print "Checking libraries..."
liblist=dsc_dirlist("/usr/lib/libSDL-1.2*")
if (liblist==[]): shutil.copy("libSDL-1.2.so.0","/usr/lib/libSDL-1.2.so.0")
liblist=dsc_dirlist("/usr/lib/libSDL_image-1.2*")
if (liblist==[]): shutil.copy("libSDL_image-1.2.so.0","/usr/lib/libSDL_image-1.2.so.0")
liblist=dsc_dirlist("/usr/lib/libSDL_net-1.2*")
if (liblist==[]): shutil.copy("libSDL_net-1.2.so.0","/usr/lib/libSDL_net-1.2.so.0")

# CREATE athome GROUP
group=open("/etc/group").read()
if (string.find(group,"athome")!=-1):
  print "Group athome already defined"
else:
  print "Creating new group 'athome'"
  os.system("/usr/sbin/groupadd -g 38475 athome")

# CREATE NEW MODELS@HOME USER
passwd=open("/etc/passwd").read()
if (string.find(passwd,"Models@Home")!=-1):
  print "User models already defined"
else:
  print "Creating new user 'models'"
  cryptpwd=crypt.crypt(password,"Mo")
  print "Encrpyted password is ",cryptpwd
  os.system("/usr/sbin/useradd -c Models@Home -d /usr/cluster -g 38475 -M -n -p "+cryptpwd+" -u 38475 models")

# CHANGE OWNER OF /usr/cluster
os.system("chown -R models.athome /usr/cluster")

print "Installation completed successfully."
