import stat


def mode_to_octal(mode):
    """
    Convert a text mode back to octal

    The opposite of stat.filemode
    """
    omode = 0

    if mode[0] == '-':
        omode |= stat.S_IFREG
    elif mode[0] == 'd':
        omode |= stat.S_IFDIR
    elif mode[0] == 'l':
        omode |= stat.S_IFLNK

    if mode[1] == 'r':
        omode |= stat.S_IRUSR
    if mode[2] == 'w':
        omode |= stat.S_IWUSR
    if mode[3] == 'x':
        omode |= stat.S_IXUSR
    elif mode[3] == 's':
        omode |= stat.S_ISUID
        omode |= stat.S_IXUSR
    elif mode[3] == 'S':
        omode |= stat.S_ISUID

    if mode[4] == 'r':
        omode |= stat.S_IRGRP
    if mode[5] == 'w':
        omode |= stat.S_IWGRP
    if mode[6] == 'x':
        omode |= stat.S_IXGRP
    elif mode[6] == 's':
        omode |= stat.S_ISGID
        omode |= stat.S_IXGRP
    elif mode[6] == 'S':
        omode |= stat.S_ISGID

    if mode[7] == 'r':
        omode |= stat.S_IROTH
    if mode[8] == 'w':
        omode |= stat.S_IWOTH
    if mode[9] == 'x':
        omode |= stat.S_IXOTH

    return omode