#!/usr/bin/env python3

import argparse
import os
import platform
import site
from sys import version_info
from textwrap import dedent

parser = argparse.ArgumentParser()
parser.add_argument('--path',
                    help='Additional paths to add to $PATH',
                    nargs='+',
                    type=str)
parser.add_argument('--without-all', action='store_true')
parser.add_argument('--no-jupyter', action='store_true')
parser.add_argument('--no-npm', action='store_true')
parser.add_argument('--no-pg', action='store_true')
parser.add_argument('--no-rust', action='store_true')
parser.add_argument('--no-userpip', action='store_true')

if __name__ == '__main__':
    args = parser.parse_args()
    paths = args.path or []

    # Set all --no-* if --without-all
    if args.without_all:
        for attr in vars(args):
            if not attr.startswith('no_'):
                continue
            setattr(args, attr, True)

    print(dedent(f'''\
        #
        # This file is generated by {os.path.abspath(__file__)}
        #
    '''))

    print(dedent('''\
        export XDG_CONFIG_HOME="$HOME"/.config
        export XDG_CACHE_HOME="$HOME"/.cache
        export XDG_DATA_HOME="$HOME"/.local/share
    '''))

    print(dedent('''\
        # zsh
        export ZDOTDIR="$XDG_CONFIG_HOME"/zsh
    '''))

    # less
    print(dedent('''\
        # less
        export LESSHISTFILE="$XDG_DATA_HOME"/less/history
    '''))

    # jupyter
    if not args.no_jupyter:
        print(dedent('''\
            # jupyter
            export IPYTHONDIR="$XDG_CONFIG_HOME"/ipython
            export JUPYTER_CONFIG_DIR="$XDG_CONFIG_HOME"/jupyter
        '''))

    # npm
    if not args.no_npm:
        print(dedent('''\
            # npm
            export NPM_CONFIG_USERCONFIG="$XDG_CONFIG_HOME"/npm/npmrc
            export NPM_CONFIG_CACHE="$XDG_CACHE_HOME"/npm
        '''))

    # PostgreSQL
    if not args.no_pg:
        print(dedent('''\
            # PostgreSQL
            export PSQLRC="$XDG_CONFIG_HOME"/pg/psqlrc
            export PSQL_HISTORY="$XDG_DATA_HOME"/pg/psql_history
        '''))

    # Rust
    if not args.no_rust:
        print(dedent('''\
            # Rust
            export CARGO_HOME="$XDG_DATA_HOME"/cargo
            export RUSTUP_HOME="$XDG_DATA_HOME"/rustup
        '''))
        paths.append('"$XDG_DATA_HOME"/cargo/bin')

    # User pip
    if not args.no_userpip:
        assert site.USER_BASE
        if platform.system() == 'Windows':
            vmajor = version_info.major
            vminor = version_info.minor
            userpath = os.path.join(site.USER_BASE, f'Python{vmajor}{vminor}',
                                    'Scripts')
        else:
            userpath = os.path.join(site.USER_BASE, 'bin')
        paths.append(f'"{userpath}"')

    if paths:
        print('typeset -U path')

        for path in paths:
            print(f'path+=({path}(N-/))')

        print('export PATH')
