#!/usr/bin/env python3

import os
import os.path
import shutil
import stat

# This script exists because I'm getting tired of
# sysadmins who don't care that the standard distribution
# of vnc uses twm, which is a useless destkop.
# Put  a generic xstartup file in $BIRCH/local/admin/xstartup,
# and newuser will automatically add this file to copy
# it to the user's $HOME/.vnc directory, if they don't
# already have and xstartup file.

def vncsetup(BIRCH):
    STARTUPFILE = str(os.path.join(BIRCH, 'local', 'admin', 'xstartup'))
    HOME = str(os.path.expanduser('~'))

    if os.path.exists(STARTUPFILE):
        if not os.path.exists(os.path.join(HOME, '.vnc')):
            print("Creating $HOME/.vnc directory")
            os.mkdir(os.path.join(HOME, '.vnc'), stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR)

        if not os.path.exists(os.path.join(HOME, '.vnc', 'xstartup')):
            print("Creating $HOME/.vnc/xstartup")
            shutil.copyfile(STARTUPFILE, os.path.join(HOME, '.vnc', 'xstartup'))
            os.chmod(os.path.join(HOME, '.vnc', 'xstartup'), stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR)

    # Oddly, I tried the symbolic link approach,
    # but on Solaris, the file isn't read by vncserver or Xvnc,
    # so you get a blank desktop.
    # cd $HOME/.vnc
    # ln -s $STARTUPFILE xstartup

if __name__=="__main__":
    if 'BIRCH' not in os.environ:
        print("ERROR - BIRCH environment not properly set")
    else:
        BIRCH = str(os.environ.get('BIRCH'))
        vncsetup(BIRCH)
