#! /bin/bash
# vim: set tabstop=4 shiftwidth=4 expandtab filetype=sh:

# mkvolinfo -- creates a (share)/.AppleDesktop/.volinfo file

makeVolInfoFile () {
    [[ -d $sharepath/.AppleDesktop ]] || mkdir $sharepath/.AppleDesktop
    touch $volinfo
    echo 'MAC_CHARSET:MAC_ROMAN' >> $volinfo
    echo 'VOL_CHARSET:UTF8' >> $volinfo
    echo 'ADOUBLE_VER:v2' >> $volinfo
    echo 'CNIDBACKEND:dbd' >> $volinfo
    echo 'CNIDDBDHOST:localhost' >> $volinfo
    echo 'CNIDDBDPORT:4700' >> $volinfo
    echo "CNID_DBPATH:$sharepath" >> $volinfo
    echo 'VOLUME_OPTS:PRODOS CACHEID' >> $volinfo
    if (( $mixedcase )); then
        echo 'VOLCASEFOLD:' >> $volinfo
    else
        echo 'VOLCASEFOLD:MTOULOWER UTOMUPPER' >> $volinfo
    fi
    echo 'EXTATTRTYPE:AFPVOL_EA_AD' >> $volinfo
    echo ".volinfo for $sharepath has been created."
}

while [[ $1 == "-f" || $1 == "-c" ]]; do
    if [[ $1 == "-f" ]]; then
        force=1
        shift
    fi

    if [[ $1 == "-c" ]]; then
        mixedcase=1
        shift
    fi
done

if [[ ${1:0:1} == "-" ]]; then

    echo "usage: mkvolinfo [-f] [-c] [shared volume path]"
    echo
    echo "-c will create the .volinfo file to specify no uppercase filename conversion"
    echo "-f will create the .volinfo file without prompting, if none exists"
    echo "If a path is specified, that is what is used, otherwise the last entry"
    echo "in /usr/local/etc/netatalk/AppleVolumes.default is used."

else
    sudo true
    if [[ $1 ]]; then
        sharepath=$(readlink -m $1)
    else
        sharepath=$(grep ^/srv/A2SERVER /usr/local/etc/netatalk/AppleVolumes.default | tail -1 | cut -d" " -f1)
    fi

    volinfo=$sharepath/.AppleDesktop/.volinfo

    if [[ ! -d $sharepath ]]; then
        echo "$sharepath does not exist."
    else
        if [[ -f $volinfo ]]; then
            echo "$volinfo already exists."
        else
            if [[ $force ]]; then
                makeVolInfoFile
            else
                echo "The .volinfo file is automatically generated when you first"
                echo "log in from an AFP (Apple II or Mac) client machine."
                echo "If you can't do this, you can create a .volinfo file now"
                echo "based on assumed defaults; proceed with caution if you have"
                echo "customized your AppleVolumes files."
                echo
                echo "If the path shown below is incorrect, you can specify"
                echo "the path to your shared volume as an argument to mkvolinfo."
                echo
                echo -n "Make .volinfo for shared volume $sharepath now? "
                read
                if [[ ${REPLY:0:1} == "y" ]] || [[ ${REPLY:0:1} == "Y" ]]; then
                    makeVolInfoFile
                fi
            fi
        fi
    fi
fi
