#!/bin/sh

CONFIG_FILE="${HOME}/.config/mksymlink.conf"
TARGET_BASE="${HOME}/.config"

usage() {
    echo "Usage: $0 [-c config_file] [-t target_base]"
    exit 1
}

while getopts "c:t:h" opt; do
    case "$opt" in
        c) CONFIG_FILE="$OPTARG" ;;
        t) TARGET_BASE="$OPTARG" ;;
        h) usage ;;
        *) usage ;;
    esac
done

if [ ! -f "$CONFIG_FILE" ]; then
    echo "Error: config file '$CONFIG_FILE' does not exist" 1>&2
    exit 2
fi

. "$CONFIG_FILE"

if [ -z "$MAIN" ]; then
    echo "Error: MAIN is not set in config file" 1>&2
    exit 3
fi

mkdir -p "$TARGET_BASE"

for entry in $list; do
    TARGET=$(echo "$entry" | cut -d= -f1)
    SRC_REL=$(echo "$entry" | cut -d= -f2)
    SRC="$MAIN/$SRC_REL"
    TARGET_PATH="$TARGET_BASE/$TARGET"

    if [ ! -e "$SRC" ]; then
        echo "Warning: source '$SRC' does not exist, skipping" 1>&2
        continue
    fi

    mkdir -p "$(dirname "$TARGET_PATH")"

    if [ -L "$TARGET_PATH" ]; then
        rm "$TARGET_PATH"
    elif [ -e "$TARGET_PATH" ]; then
        echo "Warning: target '$TARGET_PATH' exists and is not a symlink, skipping" 1>&2
        continue
    fi

    ln -s "$SRC" "$TARGET_PATH"
    echo "Created symlink: $TARGET_PATH -> $SRC"
done

