#!/usr/bin/env rc
#
# Given a program name and a configuration file name, copy the the
# file to the proper XDG directory and set up a symlink at its
# original location.  Additionally, create a script
# $XDG_CONFIG_HOME/mklinks.sh that will re-establish the symlink if
# deleted.
#
# Always run this program from your home directory.

flag e +

if (test $#* -lt 2) {
   echo Usage: `{basename $0} progname files... >[2=1]
   exit 1
}
pwd=`{pwd}
if (test $"home '!=' $"pwd) {
   echo Run `{basename $0} from your home directory: $home >[2=1]
   exit 1
}

if (~ $#XDG_CONFIG_HOME 0) config=$home/.config
if not config=$XDG_CONFIG_HOME

dir=$config/$1
mkdir -p $dir

for (sfile in $*(2-)) {
    if (test ! -r $sfile) {
       echo Cannot read from $sfile
       exit
    }
    btfile=`{echo `{basename $sfile}|sed 's/^\.//'} # Remove leading punctuation
    tfile=$dir/$"btfile

    mv $sfile $tfile
    ln -s $tfile $sfile
    if (test ! -w $config/mklinks.sh) {
        echo '#!/bin/sh'
        echo 'if [ "$HOME" != "$(pwd)" ]; then'
        echo 'echo Run the script from your home directory.'
        echo 'exit 1'
        echo 'fi'
        echo 'dir=${XDG_CONFIG_HOME:-~/.config}'
    } >> $config/mklinks.sh
    echo ln -s '$dir/'$1'/'''$btfile'''' ''''$sfile'''' >> $config/mklinks.sh
}
