#!/usr/bin/python3

import sys, os

from UmenuConf import Conf

def writeconf(fname, value):
    try:
        f = open(fname, 'w')
        f.write(value)
    except:
        print('\n======================================')
        print('Could not open {} for write, aborting.'.format(fname))
        print('=====================================.\n')
        raise
    f.close()


def usage():
	print('\nUSAGE:')
	print('  ./newmenu.sh ltr')
	print('  where ltr, a-z, is the letter of the new')
	print('  base menu to be created. If ltr matches')
	print('  an existing letter, this program will do')
	print('  print a warning and exit without creation.')



if len(sys.argv) != 2:
    print('ERROR: Must have exactly one argument.')
    usage()
    sys.exit(1)
else:
    ltr = sys.argv[1]

if len(ltr) != 1 or not ltr.islower():
    print('ERROR: Argument must be a single letter, a-z.')
    usage()
    sys.exit(1)

print('You chose to create menu {}.'.format(ltr))
cnf = Conf(['dummy', ltr])

menudir = cnf.cnf['menu']
newdir = menudir + '/' + ltr
if os.path.isdir(newdir):
    print('\nMenu {} already exists at {}'.format(ltr, newdir))
    print('Use ./newitem.py to modify it, or use a file manager or')
    print('command prompt to move it.')
    print('This program is exiting without making any changes.\n')
    sys.exit(1)

### EVERYTHING'S GOOD: MAKE ALL NECESSARY DIRECTORIES
os.mkdir(newdir)
os.mkdir(newdir + '/data')
os.mkdir(newdir + '/q')
os.mkdir(newdir + '/q/data')
dirr = newdir + '/q/data'
writeconf(dirr + '/type', 'r')
writeconf(dirr + '/choicetitle', 'Quit')
dirr = newdir + '/data'
writeconf(dirr + '/type', 'm')
#writeconf(dirr + '/choicetitle', 'Main Menu')
writeconf(dirr + '/menutitle', 'Main Menu')
writeconf(dirr + '/sort', '-q')

print('\nNew menu {} is complete at {}\n'.format(ltr, newdir))

