#!/usr/bin/env python3

import codecs
import glob
import os
import os.path
import sys


def main():
    screenlayout_dir = os.path.expanduser('~/.screenlayout')
    if not os.path.isdir(screenlayout_dir):
        os.makedirs(screenlayout_dir)

    profiles = [
        os.path.basename(f)
        for f in glob.glob(os.path.join(screenlayout_dir, '*.sh'))
    ]
    if len(profiles) == 0:
        return 0

    cur_profile = profiles[0]

    cur_profile_path = os.path.join(screenlayout_dir, '.current')
    if os.path.isfile(cur_profile_path):
        with codecs.open(cur_profile_path, encoding='utf-8') as infile:
            cur_profile = infile.read().strip()

    if cur_profile not in profiles:
        print('ERROR:{}: current profile {} not found'.format(progname,
              cur_profile), file=sys.stderr)
        cur_profile = profiles[0]

    cur_idx = profiles.index(cur_profile)
    next_idx = cur_idx + 1
    if next_idx >= (len(profiles) - 1):
        next_idx = abs(next_idx - len(profiles))

    next_profile = profiles[next_idx]
    with codecs.open(cur_profile_path, 'w', encoding='utf-8') as outfile:
        outfile.write(next_profile)

    os.execl(os.path.join(screenlayout_dir, next_profile), '--')

    return 0


if __name__ == '__main__':
    sys.exit(main())
